R:在循环

时间:2017-04-26 13:03:29

标签: r data.table

我想替换一个data.table列(col1)中的所有值。 我想在循环中尝试这样做,但只更换了几个值。 例如:

#Generate data.table
library(data.table)
dt2 <- data.table(col1=rep(c("a","b","c","d"),each=2), col2=rep(c(1,2,3,4),2),col3=rep(c(1,2,3,4),2))
> dt2
   col1 col2 col3
1:    a    1    1
2:    a    2    2
3:    b    3    3
4:    b    4    4
5:    c    1    1
6:    c    2    2
7:    d    3    3
8:    d    4    4

更改值:

#new col1 elements
new_col1 = c("WT","m1","m9","m10")
#change col1
col1_names = unique(dt$col1)
for (i in 1:length(col1_names)){
    dt2[col1==col1_names[i],col1:=new_col1[i]]
    }
> dt2
   col1 col2 col3
1:   WT    1    1
2:   WT    2    2
3:   m1    3    3
4:   m1    4    4
5:    c    1    1
6:    c    2    2
7:    d    3    3
8:    d    4    4

col1中的值仅部分替换。 任何人都可以解释它或提出更好的替代方法吗?

我试图立即更换它们,但这不能正常工作:

#generate data.table
dt2 <- data.table(col1=rep(c("a","b","c","d"),each=2), col2=rep(c(1,2,3,4),2),col3=rep(c(1,2,3,4),2))

   col1 col2 col3
1:    a    1    1
2:    a    2    2
3:    b    3    3
4:    b    4    4
5:    c    1    1
6:    c    2    2
7:    d    3    3
8:    d    4    4
#replace values
col1_names = unique(dt$col1)
dt2[col1==col1_names,col1:=new_col1]
> dt2
   col1 col2 col3
1:   WT    1    1
2:   m1    2    2
3:   m9    3    3
4:  m10    4    4
5:   WT    1    1
6:   m1    2    2
7:   m9    3    3
8:  m10    4    4

只是在没有任何条件的情况下替换值。

1 个答案:

答案 0 :(得分:1)

我同意查找表的答案。您可能想尝试:

library(data.table)

dt2 <- data.table(col1=rep(c("a","b","c","d"),each=2),
                  col2=rep(c(1,2,3,4),2),
                  col3=rep(c(1,2,3,4),2))

new_col1 <- c(a="WT",b="m1",c="m9",d="m10") # .. have to change slightly

dt2$col1<-unname(new_col1[dt2$col1])

或者使用data.table“update join”语法:

lookup = data.table(old = c("a","b","c","d"), new = c("WT","m1","m9","m10"))
dt2[lookup, on=.(col1 = old), col1 := i.new ]