In R: Find values in a data.frame that are below a certain threshold for each factor

Viewed 288

Let's say I have the following data.frame:

df = data.frame(groups =c("A","A","A","B","B","B","C","C","D","D","D","D","D"),
                values =c(1,1,5,3,2,1,7,7,9,8,7,6,5))

and another data.frame:

df_t = data.frame(groups=c("A","B","C","D"),
                  threshold=c(2,5,3,9))

Now I would like to add another column to df indicating whether the values are below the grouping threshold (TRUE) or not (FALSE). In this case:

TRUE,TRUE,FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE

I am aware that this could easily be done with a for loop. However, I think there must be a more elegant way to achieve this. I would also prefer a base R solution over dplyr or data.table.

1 Answers

Consider joining the dataset by the 'groups' and create the column

library(dplyr)
df %>% 
   left_join(df_t) %>%
    mutate(flag = values < threshold, threshold = NULL)

Or in base R use match to get the corresponding index (or a merge)

df$flag <- with(df, values <  df_t$threshold[match(groups, df_t$groups)])
df$flag
#[1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE
Related