【问题标题】:Filter multi rows by column value >0按列值过滤多行 >0
【发布时间】:2017-08-25 02:26:59
【问题描述】:

我有一个包含单词和相关值的大数据框。 我想按特定列值 >0 过滤多行。

这是我的数据框结构示例:

composition <- c(-0.2,0.2,-0.3,-0.4, 0.2, 0.1 ,0.2)
ceria <- c(0.1, 0.2,-0.4, -0.2, -0.1, -0.2, 0.2)
diamond <- c(0.3,-0.5,-0.6,-0.1, -0.1 ,-0.2,-0.15)
acid <- c( -0.1,-0.1,-0.2,-0.15, 0.1 ,0.3, 0.2)

mat <- rbind(composition, ceria, diamond, acid) 
df <- data.frame(row.names(mat), mat, row.names = NULL)
colnames(df) <- c("word","abrasive", "abrasives", "abrasivefree", 
               "abrasion" ,"slurry" ,"slurries", "slurrymethod")

df
         word abrasive abrasives abrasivefree abrasion slurry slurries slurrymethod
1 composition     -0.2       0.2         -0.3    -0.40    0.2      0.1         0.20
2       ceria      0.1       0.2         -0.4    -0.20   -0.1     -0.2         0.20
3     diamond      0.3      -0.5         -0.6    -0.10   -0.1     -0.2        -0.15
4        acid     -0.1      -0.1         -0.2    -0.15    0.1      0.3         0.20

我想分两步过滤行:

  1. 具有相同词干“slurr”的列名。(slurry/slurries/slurrymethod)
  2. 具有相同词干“abras”的列名。(abrasive/abrasives/abrasivefree wear)

我尝试过使用过滤功能来做,结果就是我想要的。

library(plyr)
df_filter_slurr  <-  filter(df,slurry>0 | slurries>0 | slurrymethod>0) %>%
                     filter(., abrasive>0 | abrasives>0 | abrasivefree>0 | abrasion>0) 

         word abrasive abrasives abrasivefree abrasion slurry slurries slurrymethod
1 composition     -0.2       0.2         -0.3     -0.4    0.2      0.1          0.2
2       ceria      0.1       0.2         -0.4     -0.2   -0.1     -0.2          0.2

但是过滤器函数需要定义每个列名来过滤。 我认为代码对我来说太长了。 还有其他更高效的方法吗?

【问题讨论】:

    标签: r dataframe filter


    【解决方案1】:

    我们可以使用dplyr 包中的filter_atstarts_with 是一种用字符串模式指定列的方法,any_vars 可以指定过滤条件。

    library(dplyr)
    
    df2 <- df %>%
      filter_at(vars(starts_with("slurr")), any_vars(. > 0)) %>%
      filter_at(vars(starts_with("abras")), any_vars(. > 0))
    
    df2
             word abrasive abrasives abrasivefree abrasion slurry slurries slurrymethod
    1 composition     -0.2       0.2         -0.3     -0.4    0.2      0.1          0.2
    2       ceria      0.1       0.2         -0.4     -0.2   -0.1     -0.2          0.2
    

    【讨论】:

    • 哇~这段代码太棒了!感谢您的大力帮助并迅速回答。
    猜你喜欢
    • 2017-02-11
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多