使用data.table将NA分配给变量组 [英] Assigning NA to groups of variables using data.table
本文介绍了使用data.table将NA分配给变量组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用data.table为一组变量(9个变量,从p05_1到p05_9)分配特定值(0和99)的NA。我没有得到任何错误,但是当我使用这个代码没有发生任何事情:
I am trying to assign NA for specific values (0 and 99) to a group of variables (9 variables, from p05_1 to p05_9) using data.table. I don't get any error, but nothing happens when I use this code:
这里一个简单的例子:
v_1 <- c(0,0,1,2,3,4,4,99)
v_2 <- c(1,2,2,2,3,99,1,0)
dat <- data.table(v_1,v_2)
for(n in 1:9) {
char <- sprintf('p05_%s', n)
st[eval(parse(text=char)) %in% c(0,99), eval(parse(text=char)) := NA_integer_]
}
最好。
推荐答案
这里是使用replace()函数的另一个选择:
Here's another alternative using the replace() function:
> dat[, lapply(list(v_1, v_2), function(x) replace(x, x %in% c(0, 99), NA_integer_))]
V1 V2
1: NA 1
2: NA 2
3: 1 2
4: 2 2
5: 3 3
6: 4 NA
7: 4 1
8: NA NA
这篇关于使用data.table将NA分配给变量组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文