我有以下列表
catlist <- list(c("< 30 days","1-3 months","4-6 months"),c("7-12 months"),c("1-3 years"),
c("4-5 years","5+ years","never"))
我给的名字
names(catlist) <- 1:length(catlist)
此外,我还有一个data.table
library(data.table)
tmp <- data.table(variable = c("never","1-3 years"))
我想做的是在 tmp
中创建一个新变量 (new_variable
),它的值将是 catlist 的名称
其中的值
变量
的落入
所以最后我想以这个结束
> tmp
variable new_variable
1: never 4
2: 1-3 years 3
我尝试创建一个函数,但它不起作用
trans_dummy_multiple <- function(dt, var, catlist){
dt <- tmp # for testing
var <- "variable" # for testing
catlist <- list(c("< 30 days","1-3 months","4-6 months"),c("7-12 months"),c("1-3 years"),
c("4-5 years","5+ years","never")) # for testing
names(catlist) <- 1:length(catlist)
dt[,new_variable:=lapply(catlist,function(x){if(x%in%get(var)){names(x)}})]
}
最佳答案
尝试:
scl<-setDT(stack(catlist))
scl[tmp,on=c(values="variable")]
# values ind
#1: never 4
#2: 1-3 years 3
关于r - 如何查看元素是否包含在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572314/