2017-06-22 93 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,]