I am stuck. I have a Dataframe:
test_df <- tibble(a = c(1,1,1), b = c(1,NA,2), c = c(1,1,1), d = c("a","b","c"))
test_df
# A tibble: 3 x 4
a b c d
<dbl> <dbl> <dbl> <chr>
1 1 1 1 a
2 1 NA 1 b
3 1 2 1 c
And I want to create a new column, indicating, if a, b and c have the same value (ignoring NAs).
Should look like this:
# A tibble: 3 x 5
a b c d equal
<dbl> <dbl> <dbl> <chr> <lgl>
1 1 1 1 a TRUE
2 1 NA 1 b TRUE
3 1 2 1 c FALSE
I've been experimenting with "unique", but I guess, I am doing it wrong:
test_df %>% mutate(equal = case_when(unique(a, b, c) == 1 ~ TRUE,
TRUE ~ FALSE))
# A tibble: 3 x 5
a b c d equal
<dbl> <dbl> <dbl> <chr> <lgl>
1 1 1 1 a TRUE
2 1 NA 1 b TRUE
3 1 2 1 c TRUE
Update
I used the resulting dataframe to calculate mean scores, using summarise_at()
. This returned the exact same dataframe. Reading this thread with a similar problem, I realized, that I have to extend the code with ungroup()
, to get a df that I can summarize later:
test_df %>%
rowwise() %>%
mutate(equal = sd(c(a, b, c), na.rm = TRUE) == 0) %>%
ungroup()