Search values across all columns in R data frame

后端 未结 4 1019
夕颜
夕颜 2020-12-21 11:45

Here\'s a sample data frame.

df = data.frame(company = c(\'a\', \'b\', \'c\', \'d\'),
                 bond = c(0.2, 1, 0.3, 0),
                 equity = c         


        
相关标签:
4条回答
  • 2020-12-21 12:00

    We can also use Reduce with ==

    res <- df[Reduce(`+`, lapply(df[-1], `==`, 1))!=0,]
    res
    #   company bond equity cash
    #2       b    1      0    0
    #4       d    0      1    0
    
    res$company
    #[1] b d
    #Levels: a b c d
    
    0 讨论(0)
  • 2020-12-21 12:02

    Another option:

    df[unique(row(df[-1])[df[-1] == 1L]),]
    #  company bond equity cash
    #2       b    1      0    0
    #4       d    0      1    0
    
    df$company[unique(row(df[-1])[df[-1] == 1L])]
    #[1] b d
    #Levels: a b c d
    
    0 讨论(0)
  • 2020-12-21 12:20

    Use rowSums to check the logic data frame should work:

    df[rowSums(df[-1] == 1.0) != 0, 'company']
    [1] b d
    Levels: a b c d
    
    0 讨论(0)
  • 2020-12-21 12:20
    var <- df %>% select(bond:cash) %>% names
    plyr::ldply(var, function(x) paste("filter(df,", x, "==1)") %>% parse(text=.) %>% eval)
      company bond equity cash
    1       b    1      0    0
    2       d    0      1    0
    
    0 讨论(0)
提交回复
热议问题