5

我有一个简单的数据框列转换,可以使用 if/else 循环来完成,但我想知道是否有更好的方法来做到这一点。

初始数据帧是,

 df <-data.frame(cbind(x=rep(10:15,3), y=0:8))
 df
    x y
1  10 0
2  11 1
3  12 2
4  13 3
5  14 4
6  15 5
7  10 6
8  11 7
9  12 8
10 13 0
11 14 1
12 15 2
13 10 3
14 11 4
15 12 5
16 13 6
17 14 7
18 15 8

我需要做的是替换“y”列中的值,这样

'0' gets replaced with '2',
'1' gets replaced with '2.2',
'2' gets replaced with '2.4',
...
...
'6' gets replaced with '3.2'
'7' gets replaced with '3.3'
'8' gets replaced with '10'

所以我最终会得到类似的东西,

> df
    x    y
1  10  2.0
2  11  2.2
3  12  2.4
4  13  2.6
5  14  2.8
6  15  3.0
7  10  3.2
8  11  3.3
9  12 10.0
10 13  2.0
11 14  2.2
12 15  2.4
13 10  2.6
14 11  2.8
15 12  3.0
16 13  3.2
17 14  3.3
18 15 10.0

我已经搜索并找到了几个建议,但无法让它们发挥作用。其中一项尝试是,

> levels(factor(df$y)) <- c(2,2.2,2.4,2.6,2.8,3,3.2,3.3,10)

Error in levels(factor(df$y)) <- c(2, 2.2, 2.4, 2.6, 2.8, 3, 3.2, 3.3,  : 
  could not find function "factor<-"

但我收到上面显示的错误消息。

谁能帮我这个?

4

2 回答 2

5

y+1使用作为替换索引的事实

就像是

replacement <- c(2,2.2,2.4,2.6,2.8,3,3.2,3.3,10)
df <- within(df, z <- replacement[y+1])

或者,data.table用于合成糖和记忆效率

library(data.table)
DT <- as.data.table(df)

DT[, z := replacement[y+1]]
于 2012-10-15T02:06:06.337 回答
3

怎么样:

mylevels <- c(2,2.2,2.4,2.6,2.8,3,3.2,3.3,10)
df$z <- as.numeric(as.character(factor(df$y,labels=mylevels)))

这也符合您想要的结果:

transform(df,z=ifelse(y==7,3.3,ifelse(y==8,10,2+y/5)))
于 2012-10-15T02:04:13.447 回答