Using filter_ in dplyr where both field and value are in variables

后端 未结 4 1433
离开以前
离开以前 2020-12-15 09:48

I want to filter a dataframe using a field which is defined in a variable, to select a value that is also in a variable. Say I have

df <- data.frame(V=c(6         


        
4条回答
  •  情书的邮戳
    2020-12-15 10:09

    You can try with interp from lazyeval

     library(lazyeval)
     library(dplyr)
     df %>%
         filter_(interp(~v==sval, v=as.name(fld)))
     #   V Unhappy
     #1 1       Y
     #2 5       Y
     #3 3       Y
    

    For multiple key/value pairs, I found this to be working but I think a better way should be there.

      df1 %>% 
        filter_(interp(~v==sval1[1] & y ==sval1[2], 
               .values=list(v=as.name(fld1[1]), y= as.name(fld1[2]))))
     #  V Unhappy Col2
     #1 1       Y    B
     #2 5       Y    B
    

    For these cases, I find the base R option to be easier. For example, if we are trying to filter the rows based on the 'key' variables in 'fld1' with corresponding values in 'sval1', one option is using Map. We subset the dataset (df1[fld1]) and apply the FUN (==) to each column of df1[f1d1] with corresponding value in 'sval1' and use the & with Reduce to get a logical vector that can be used to filter the rows of 'df1'.

     df1[Reduce(`&`, Map(`==`, df1[fld1],sval1)),]
     #   V Unhappy Col2
     # 2 1       Y    B
      #3 5       Y    B
    

    data

    df1 <- cbind(df, Col2= c("A", "B", "B", "C", "A"))
    fld1 <- c(fld, 'Col2')
    sval1 <- c(sval, 'B')    
    

提交回复
热议问题