我有一个简单的数据框列转换,可以使用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<-"

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

谁能帮我这个?

最佳答案

使用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]]

关于r - 如何更改数据框中的列值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12888363/

10-12 17:34
查看更多