我有data.table
名为md
,看起来像这样
group_1 group_2
a a
b a
b b
c c
我使用以下代码:
groups <- c("group_1","group_2")
for (group in groups)
{
md[!get(group)=="a",get(group):="b"]
md[,get(group):=factor(x = get(group),levels = c("a","b"),ordered = T)]
}
因此,如果每行的值不是“a”,我想要data.table
中的两列,然后将值替换为“b”,然后向其添加有序级别。
但我收到错误Error in get(group): object 'group_1' not found
有什么想法吗?
答案 0 :(得分:1)
另一种选择是使用set
for(group in groups){
set(md, i = which(md[[group]] !='a'), j = group, value = 'b')
set(md, i = NULL, j = group, value = factor(md[[group]], levels = c('a', 'b'),
ordered = TRUE))
}
md
# group_1 group_2
#1: a a
#2: b a
#3: b b
#4: b b