LoginSignup
1

More than 3 years have passed since last update.

R言語のfor文で引数にデータを割り当てたり、読み込んだりする

Last updated at Posted at 2020-01-17

for文中でデータを成型して、変数に入れたい

いちいちcsvに吐き出して後で読み込んでもいいのですが、assignが使えたら少しスマートなコードも書けるかも。

※2019-01-18追記
for文中でのfor文への割り当てとしてirisデータを使っていきます。

for( i in 1:10){
    assign(paste0("iris_row", i), iris[i,])
}

paste0で指定した文字列を引数名にしてデータを割り当てられる。

iris_row1

結果出力は

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa

pasteで名付けた引数に割り当てられていることが分かる。

get関数

get関数で引数名をpaste関数と組み合わせて呼び出せる。
決まったフォーマットで命名した引数を呼び出すときに便利

get(paste0("iris_row", 1))

上記のiris_row1と同じ結果が返ってくる

引数名を指定できるということは、

for( i in 1:10){
    print(get(paste0("iris_row", i)))
}
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
2          4.9           3          1.4         0.2  setosa
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
3          4.7         3.2          1.3         0.2  setosa
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
4          4.6         3.1          1.5         0.2  setosa
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5            5         3.6          1.4         0.2  setosa
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
6          5.4         3.9          1.7         0.4  setosa
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
7          4.6         3.4          1.4         0.3  setosa
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
8            5         3.4          1.5         0.2  setosa
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
9          4.4         2.9          1.4         0.2  setosa
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
10          4.9         3.1          1.5         0.1  setosa

繰り返しで表示もできる。
さらにprintが適応できるということは

for( i in 1:10 ){
    write.csv(get(paste0("iris_row", i)), paste0(i,".csv"))
}

※2019-01-18 write → write.csvに修正

引数をfor文で指定しながらcsvに変換もできる。

以上

スマートなコードたらんことを。

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
1