Reputation: 483
I have a big data frame contains words and correlation value. I want to filter multi rows by specific columns value >0.
Here is my data frame structure example:
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
I want to filter rows by two step:
I have tried use filter function to do and the result is what I want.
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
But the filter function need to define each column names to filter. I think the code is too lengthy for me. Is there have other way more efficient?
Upvotes: 2
Views: 604
Reputation: 39154
We can use filter_at
from the dplyr
package. starts_with
is a way to specify columns with a string pattern, any_vars
can specify the condition for the filter.
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
Upvotes: 3