Update: Why is tibble() needed:
Without as_tibble()
or tibble()
or data.frame()
it won't work:
Your table:
> class(df)
[1] "grouped_df" "tbl_df" "tbl" "data.frame"
- Without
as_tibble()
or tibble()
or data.frame()
-> won't work:
>df %>%
mutate(valid = ifelse(rowSums(select(., contains("c_")))==1, TRUE, FALSE))
Adding missing grouping variables: `id`
Error in `mutate()`:
! Problem while computing `valid = ifelse(rowSums(select(.,
contains("c_"))) == 1, TRUE, FALSE)`.
x `valid` must be size 1, not 3.
i The error occurred in group 1: id = 1.
- With
as_tibble()
or tibble()
or data.frame()
-> it will work:
df %>%
data.frame() %>%
mutate(valid = ifelse(rowSums(select(., contains("c_")))==1, TRUE, FALSE))
#or
df %>%
tibble() %>%
mutate(valid = ifelse(rowSums(select(., contains("c_")))==1, TRUE, FALSE))
First answer:
If we want to do it with select: Here is an out of the box approach:
library(tibble)
library(dplyr)
df %>%
as_tibble() %>%
mutate(valid = ifelse(rowSums(.[2:3])==1, TRUE, FALSE))
or
library(tibble)
library(dplyr)
df %>%
as_tibble() %>%
mutate(valid = ifelse(rowSums(select(., contains("c_")))==1, TRUE, FALSE))
# A tibble: 3 x 4
id c_1 c_2 valid
<dbl> <lgl> <lgl> <lgl>
1 1 TRUE FALSE TRUE
2 2 TRUE FALSE TRUE
3 3 FALSE TRUE TRUE