How to mutate a new column based on two values from the same column in R

Viewed 35

I want to create a new column where if the length of one group in a column is greater than 25, it would be classified as different, and if it's not, it would be classified as same.

For example, I have a data table:

#    read   condition   type      
#1      1      square    100   
#2      1      square    100   
#3      1      square    100   
#4      1       round    200  
#5      1       round    200  
#6      1       round    200  
#7      2      square    150       
#8      2      square    150       
#9      2       round    160       
#10     2       round    160       

I was thinking along the lines of a pseudocode:

data <- data %>%
group_by(read, condition) %>%
mutate(length = if_else("type of condition" == "round" > 25, different, same))

with dplyr, but I wasn't sure how to select the group to produce this result. Since this is only part of the data (reads 1 and 2), I need a way that I can apply to read = 3, 4, 5, etc. that contain the same "square" and "round" conditions. Is this doable with base R or dplyr?

Desired result:

#    read   condition   type      length
#1      1      square    100   different
#2      1      square    100   different
#3      1      square    100   different
#4      1       round    200   different
#5      1       round    200   different
#6      1       round    200   different
#7      2      square    150        same
#8      2      square    150        same
#9      2       round    160        same
#10     2       round    160        same
1 Answers

We may need to get the sum of logical expression

library(dplyr)
data %>%
  group_by(read) %>%
   mutate(length = if_else(sum(condition == "round",
                      na.rm = TRUE) > 25, # condition
              "different", # true
                 "same") # false
      )
Related