0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

R > データ操作 / データフレーム > read.tableで読込んだリストの一部の値を四捨五入する

Last updated at Posted at 2016-09-23
動作環境
RStudio 0.99.903 on Windows 7 pro
R version 3.3.1

R機能マップ
http://qiita.com/7of9/items/0f911bcb95d3a8bbd703

read.table()で読込んだリストの一部を四捨五入する。

sample.csv
A,B,C
hello,1.5,3.2
1 2 3
A B C
hello 1.5 3.2

上記のうち、右下の2列目と3列目の数値だけを四捨五入したい。
(本当の対象ファイルでは2行目の7列目から326列目を処理したい)。

  • 一旦、xtableすべてをouttblにコピー
  • 四捨五入したい範囲だけlapply()を使用
> xtable<-read.table("sample.csv", sep=",", stringsAsFactors = F)
> outtbl<-xtable
> outtbl[2:2,2:3]<-lapply(as.numeric(xtable[2:2,2:3]),round)
> View(outtbl)

qiita.png

「はまる」可能性があるのでstringsAsFactors はFalseにしない方がいいという情報もあるが、今の僕の理解力では上記の方法ぐらいしかできない。

四捨五入の結果は以下のようにしてcsv出力する。
参考 http://statsbeginner.hatenablog.com/entry/2014/08/31/230758
ただし、V1,V2,...といった行がついてしまうので、そこは手動で消した。

write.csv(outtbl, "out.csv", quote = F, row.names = F)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?