2017-06-22 89 views
0

我正在尝试动态子集一些数据框。我有三个二进制列,我想一个子集,当第一列== 1,其他第二,当列== 1,等...R将一个变量评估为一个循环

这里我的代码:

arcep=data.table(arcep) 
techno=c("2G","3G","4G") 
for(value in techno){ 
    index=colnames(arcep)[grep(value,colnames(arcep))] 
    print(index) 
    set1=subset(arcep,arcep[,index]==1) 
    print(dim(set1)) 
    assign(set1,paste0("ARCEP_",value)) 
} 

错误:

Error in `[.data.table`(arcep, , index) : 
    j (the 2nd argument inside [...]) is a single symbol but column name 'index' is not found. Perhaps you intended DT[,..index] or DT[,index,with=FALSE]. This difference to data.frame is deliberate and explained in FAQ 1.1. 

在索引之前添加“eval”不会改变任何内容。我不明白,我怎么能解决这个问题?

enter code here index = grep(value,colnames(arcep)) (所以返回列号)不起作用,同样的问题:它寻找名为“index”的列。我也尝试在子集函数中提供grep(value,colnames(arcep))作为直接参数,但它不起作用。

我也试图与get(index)

Error in get(index) : invalid first argument 

编辑

这里的结果与一些打印:

for(value in techno){ 
    print(class(grep(value,colnames(arcep)))) 

整数

print(grep(value,colnames(arcep))) 
set1=arcep[,grep(value,colnames(arcep))] 
print(dim(set1)) 

NULL

回答

0
x<-data.frame(col1=c(1,2,3,1,5,17,1,9),col2=c(1,2,3,6,2,4,1,7),col3=c(1,2,3,5,1,2,5,6)) 

这将子集中的第一和第二列仅

x[x[,1]==1&x[,2]==1,]