LoginSignup
1
2

More than 5 years have passed since last update.

R初心者のための!Rで型を複数列まとめて変更する方法

Posted at

データの型まとめて変換する方法

データの方を確認する方法について、書きましたが今回は「まとめて変換する方法」です。

> sapply(table, class)
     unit     price      freq      temp 
"numeric" "numeric" "numeric" "numeric" 

> table[, 1:4] <- apply(table[,1:4], 2, as.integer)

> sapply(table, class)
     unit     price      freq      temp 
"integer" "integer" "integer" "integer" 

こんな具合に、applyを使うことでまとめて変換できます。
unitとfreqをだけを変えたければ、

> target <- c("unit", "freq")

> table[, target] <- apply(table[, target], 2, as.numeric)

> sapply(table, class)
     unit     price      freq      temp 
"numeric" "integer" "numeric" "integer" 

このように任意の列だけ変更できます。

1
2
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
1
2