Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何查看元素是否包含在列表中_R_Data.table - Fatal编程技术网

R 如何查看元素是否包含在列表中

R 如何查看元素是否包含在列表中,r,data.table,R,Data.table,我有以下清单 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")) 我想做的是在tmp中创建一个新变量(new_variable),该变量的值为catlist的名称,其中 变量的 所以最后我想以这个结束 > tmp variable new

我有以下清单

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"))
我想做的是在
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)}})]


}

trans\u dummy\u multiple您可以使用
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
尝试:


scl这里有一个带有
melt

setDT(melt(catlist))[tmp, on = .(value = variable)]
#       value L1
#1      never  4
#2: 1-3 years  3

我可以使用
utils::stack()
函数和
dplyr
(我没有
data.table
的经验)来实现这一点。将此添加到您的代码中:

require(dplyr)

catlist2 <- catlist %>%
  stack()

tmp <- tmp %>%
  left_join(y = catlist2, by = c("variable" = "values"))

#   variable ind
# 1     never   4
# 2 1-3 years   3
require(dplyr)
catlist2%
堆栈()
tmp%
左连接(y=catlist2,by=c(“变量”=“值”))
#变量ind
#1永远不会4
#2 1-3年3

您认为有什么方法可以避免for循环吗?因此
列是
数据表中(现有)变量的名称。
对吗?我使用
堆栈时出错:
文件系统中不存在<30天],并且未被识别为受支持的数据集名称。
您收到了一些我们不知道的加载包。使用
utils::stack
并检查您正在使用的包。翻译为“在tmp中创建新变量”,我想有
tmp[,新变量:=scl[tmp,on=c(values=“variable”),ind]
   variable new_variable
1     never            4
2 1-3 years            3
scl<-setDT(stack(catlist))
scl[tmp,on=c(values="variable")]
#      values ind
#1:     never   4
#2: 1-3 years   3
setDT(melt(catlist))[tmp, on = .(value = variable)]
#       value L1
#1      never  4
#2: 1-3 years  3
require(dplyr)

catlist2 <- catlist %>%
  stack()

tmp <- tmp %>%
  left_join(y = catlist2, by = c("variable" = "values"))

#   variable ind
# 1     never   4
# 2 1-3 years   3