按列值> 0过滤多行

时间:2017-08-25 02:26:59

标签: r dataframe filter

我有一个包含单词和相关值的大数据框。 我想按特定列值> 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”的柱名。(浆液/浆液/浆液方法)
  2. 具有相同阀杆“磨损”的柱名称(磨料/磨料/无磨料磨损)
  3. 我尝试过使用过滤功能,结果就是我想要的。

    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
    

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

1 个答案:

答案 0 :(得分:3)

我们可以使用filter_at包中的dplyrstarts_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
相关问题