[英]Filter multi rows by column value >0
我有一個包含字和相關值的大數據框。 我想按> 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
我想通過兩步來篩選行:
我嘗試使用過濾器功能來做,結果就是我想要的。
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
但是filter函數需要定義每個要過濾的列名。 我認為代碼對我來說太長了。 有沒有其他更有效的方法?
我們可以使用filter_at
從dplyr
包。 starts_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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.