简体   繁体   中英

R evaluate a variable into a loop

I am trying to dynamically subset some dataframes. I have three binary columns, I want a subset when first column==1, an other when second column ==1, etc...

Here my code:

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:

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.

Adding "eval" before index doesn't change anything. I don't understand, how could I fix this problem?

enter code here index=grep(value,colnames(arcep)) (so return the number of the column) doesn't work, same problem: it looks for a column named "index". I also tried to provide grep(value,colnames(arcep)) as a direct argument in the subset function, and it doesn't work.

I have also tried with get(index)

Error in get(index) : invalid first argument

EDIT

Here the result with some print:

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

integer

print(grep(value,colnames(arcep)))

4

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

NULL

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,]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM