I've seen the question How to use the which() function with a pipe %>% but it doesn't encapsulate the problem I am having. I would like to access the column names of a dataframe inside the which() function. For example, given the dataframe:
> df <- data.frame(ID=1:6, col1=c(0,1,2,0,5,0), col2=c("A1", "A2", "B1", "B2","C1", "A3"))
> df
ID col1 col2
1 1 0 A1
2 2 1 A2
3 3 2 B1
4 4 0 B2
5 5 5 C1
6 6 0 A3
I can identify which rows in col1 have zero entries by doing:
row_zero <- which(df$col1 == 0 & grepl("A", df$col2, fixed=TRUE))
> row_zero
[1] 1 6
In order to avoid the repeated use of df$, I would like to apply a pipe. I tried the following (even using the tip from How to use the which() function with a pipe %>%), but it does not work:
> row_zero <- df %>% which(col1 == 0 & grepl("A", col2, fixed=TRUE))
Error in which(., col1 == 0 & grepl("A", col2, fixed = TRUE)) :
argument to 'which' is not logical
> row_zero <- df %>% { which(col1 == 0 & grepl("A", col2, fixed=TRUE)) }
Error: object 'col1' not found
Any suggestions on how to make the above work? Thank you.
reframe, e.g.df %>% reframe(which(col1 == 0 & grepl("A", col2, fixed=TRUE))) %>% unlist(use.names=F). For other data manipulation purposesmutateandsummarizeare common dplyr pipe verbs.%>%suggestsdplyr, please be specific if you are intending to use it or if you're trying to stay with base. Thanks!where(.)orif_any(.)or similar can be used.