1

データ フレームがあり、いくつかの列の値を文字列から整数に変更したいだけです。

Rでこれを達成するにはどうすればよいですか?

これが私のデータだとします:

data.frame(
    X = sample(1:10),
    Y = sample(c("yes", "no"), 10, replace = TRUE),
    Z = sample(c("yes", "no"), 10, replace = TRUE),
    ZZ = sample(c("yes", "no"), 10, replace = TRUE))

そして私は変更したい:

指定された関数 f で列 Y を変更します [例。関数 f 2 列目の「はい」を 2 に、「いいえ」を 1 に変更します]

そのような機能の例

f <- function (x) {
 if(x == "yes") {
   return 2;
 }
 else {
   return 11;
 }
}

指定された関数 g で列 ZZ を変更します [例: 関数 g 4 列目の「はい」を 3 に、「いいえ」を 4 に変更]

4

1 に答える 1

3

ここで function を使用したソリューションifelse()

df<-data.frame(
  X = sample(1:10),
  Y = sample(c("yes", "no"), 10, replace = TRUE),
  Z = sample(c("yes", "no"), 10, replace = TRUE),
  ZZ = sample(c("yes", "no"), 10, replace = TRUE))

df$Y=as.integer(ifelse(df$Y=="yes",2,1))
df$ZZ=as.integer(ifelse(df$ZZ=="yes",3,4))
str(df)
'data.frame':   10 obs. of  4 variables:
 $ X : int  9 4 8 5 1 7 2 10 6 3
 $ Y : int  2 2 1 1 2 1 2 1 1 1
 $ Z : Factor w/ 2 levels "no","yes": 2 1 2 2 1 2 2 1 1 1
 $ ZZ: int  3 3 4 3 3 3 3 4 4 3

編集

関数を作成fg、同じタスクを実行するには

f<-function(x){
  as.integer(ifelse(x=="yes",2,1))
}

g<-function(x){
  as.integer(ifelse(x=="yes",3,4))
}

df$Y=f(df$Y)
df$ZZ=g(df$ZZ)
于 2012-12-28T11:05:33.310 に答える