Reputation: 1702
I have a single row dataframe:
df <- structure(list(who = "Tom", who2 = "Tom", who3 = "Harry", how_many = 48,
reserve = "Mary"), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L))
# A tibble: 1 x 5
who who2 who3 how_many reserve
<chr> <chr> <chr> <dbl> <chr>
1 Tom Tom Harry 48 Mary
I'd like to subset columns by condition, but I get the error:
Error: condition must be a logical, not list
from the code below.
df %>%
if_else(who == who2, select(who3), select(how_many, reserve))
I think I understand why I'm getting the error - this code would not be valid if there was more than 1 row, but can't think of another way how to do this in a chain of dplyr
piped functions.
Upvotes: 0
Views: 139
Reputation: 206197
One way it to pipe the data into an expression block and then run more standard code to conditionally select what columns you want.
df %>% {if (pull(., who )==pull(., who2 )) {
select(., who3)
} else {
select(., how_many, reserve)
}}
Upvotes: 3