r - Looping over column names like DF$j -


i have following data frame:

    id  a1  a2  a3    a4     b1      b2      b3      b4    1  id1   1   2   1     1      1       1       2       2 2  id2   2   2   1     1      2      na       2       1 3  id3   2   2   1     2      1       1      na       2           4  id4   1   1   1     1      1      na      na       2          5  id5   2   2   1     1     na      na       2      na        6  id6   1   1   1     1      2       2       2       2    

i want extract rows data frame meeting specific conditions each combination of , b. these conditions:

  • pp: value 2 present in a-type column + value 2 present in b-type column

  • pa: value 2 present in a-type column + value 1 present in b-type column

  • ap: value 1 present in a-type column + value 2 present in b-type column

  • aa: value 1 present in a-type column + value 1 present in b-type column

this wrote:

a <- colnames(dataframe)[2:5] # = a1, a2, a3 , a4 b <- colnames(dataframe)[6:9]  # b = b1, b2, b3 , b4  (a in a) {      (b in b) {          pp <- dataframe[dataframe$a=='2' & dataframe$b=='2' , ]          pa <- dataframe[dataframe$a=='2' & dataframe$b=='1' , ]          ap <- dataframe[dataframe$a=='1' & dataframe$b=='2' , ]          aa <- dataframe[dataframe$a=='1' & dataframe$b=='1' , ]         print(head(pp)) #to have preview     }  } 

however new data frames empty , don't understand why. ideally, the first loop (with a=a1 , b=b1) therefore output:

pp:

     id  a1  a2  a3  a4  b1  b2  b3  b4  2  id2   2   2   1   1   2  na   2   1 

pa:

    id  a1  a2  a3  a4  b1  b2  b3  b4 3  id3   2   2   1   2   1   1  na   2   

ap:

    id  a1  a2  a3  a4  b1  b2  b3  b4 6  id6   1   1   1   1   2   2   2   2    

aa:

    id  a1  a2  a3  a4  b1  b2  b3  b4 1  id1   1   2   1   1   1   1   2   2 

i hope can help. thanks.

the dollar sign extraction creating problem. not meant passing of variables in dataframe$a. because a not actual name. trying pass variable name on it. operator literal a column , not find it. try dataframe[,a]


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -