Joshua Culpepper
Joshua Culpepper

Reputation: 71

Logical test to determine if a value exists in a grouped dataframe in R (tidy solution)

I would like to test if a value exists between two values in a large dataframe that I've grouped by a factor. Basically, I have a column with numerical values and I'd like to test if any rows have a value between -5 and 5. Here's an example:

x <- tibble(value = c(-10, 8, 10, 0, 6, 10), group = c('A', 'A', 'A', 'B', 'B', 'B')) %>%
  group_by(group) %>%
  mutate(
    logical_test = if_else(any(value >= -5) & any(value <= 5), TRUE, FALSE)
  )

Group A should be FALSE. It does not have a value between -5 and 5; however, the test shows TRUE. I'm unsure what I'm doing wrong. Is any() not the correct function here?

Any assistance is greatly appreciated.

Upvotes: 1

Views: 1270

Answers (1)

AndrewGB
AndrewGB

Reputation: 16856

As pointed out in the comments, you only need to use any once and do not need ifelse as using any will already return a logical.

library(dplyr)

x <-
  tibble(value = c(-10, 8, 10, 0, 6, 10),
         group = c('A', 'A', 'A', 'B', 'B', 'B')) 

x %>%
  group_by(group) %>%
  mutate(logical_test = any(value >= -5 & value <= 5))

Output

  value group logical_test
  <dbl> <chr> <lgl>       
1   -10 A     FALSE       
2     8 A     FALSE       
3    10 A     FALSE       
4     0 B     TRUE        
5     6 B     TRUE        
6    10 B     TRUE  

Or with data.table:

library(data.table)

setDT(x)[, test := any(value >= -5 & value <= 5), by = group]

Or with base R:

x$logical_test <- as.logical(ave(x$value, x$group, FUN = \(x) any(x >= -5 & x <= 5)))

Upvotes: 3

Related Questions