我有以下清单
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"))我想要做的是,在new_variable中创建一个新变量( tmp ),它将以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)}})]
}发布于 2018-03-30 10:17:40
尝试:
scl<-setDT(stack(catlist))
scl[tmp,on=c(values="variable")]
# values ind
#1: never 4
#2: 1-3 years 3发布于 2018-03-30 10:15:19
您可以使用grep解决方案
tmp <- data.frame(variable = c("never","1-3 years"), stringsAsFactors = F)
df <- transform(tmp, new_variable = sapply(df$variable, function(item) grep(item, catlist)))
df这会产生
variable new_variable
1 never 4
2 1-3 years 3发布于 2018-03-30 10:19:53
下面是使用melt的一个选项
setDT(melt(catlist))[tmp, on = .(value = variable)]
# value L1
#1 never 4
#2: 1-3 years 3https://stackoverflow.com/questions/49572314
复制相似问题