Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if variables have equal value rowwise

Tags:

r

dplyr

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()
like image 704
MBeck Avatar asked Apr 01 '26 03:04

MBeck


2 Answers

One option could be:

test_df %>%
 rowwise() %>%
 mutate(equal = sd(c(a, b, c), na.rm = TRUE) == 0)

      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
like image 70
tmfmnk Avatar answered Apr 02 '26 20:04

tmfmnk


test_df %>%
    rowwise() %>%
    mutate(i = c(a, b, c) %>% unique %>% na.omit %>% length == 1)
like image 43
d.b Avatar answered Apr 02 '26 20:04

d.b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!