LoginSignup
28
37

More than 5 years have passed since last update.

R:データフレームの列を入れ替える・削除する。

Posted at

データフレームの項目の順序を入れ替えたり削除したりする方法です。
いくつか方法があるけど、これが個人的に一番楽かな。
毎度おなじみirisさんで確認。

最初の状態。

> iris[1,]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa

1列目と2列目の入れ替え。

> iris2 <- iris[,c(2,1,3,4,5)]
> iris2[1,]
  Sepal.Width Sepal.Length Petal.Length Petal.Width Species
1         3.5          5.1          1.4         0.2  setosa

1列目、2列目だけ残す。c(1:2)でも可。

> iris2 <- iris[,c(1,2)]
> iris2[1,]
  Sepal.Length Sepal.Width
1          5.1         3.5

1列目、2列目だけ残す。他の列を削除する形式。

> iris2 <- iris[,c(-3,-4,-5)]
> iris2[1,]
  Sepal.Length Sepal.Width
1          5.1         3.5
28
37
1

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
28
37