Home > Mobile >  Mutate a variable for many rows in a group based on one row R
Mutate a variable for many rows in a group based on one row R

Time:10-08

I'm looking to code a new variable for multiple rows in a group based on one row in the group and not finding a working solution.

Minimal working example:

df <- data.frame("participant" = c("1", "1", "1", "1", "1", "1", "1", "1", 
                                   "2", "2", "2", "2", "2", "2", "2", "2"), 
                 "group" = c("1111", "1111", "1111", "1111", "1113", "1113", "1113", "1114",
                             "1111", "1111", "1113", "1113", "1113", "1113", "1113", "1113"),
                 "item" = c("a", "b", "c", "d", "e", "f", "g", "h",
                            "i", "j", "k", "l", "m", "n", "o", "p"),
                 "value" = c("xyz", "hlm", "test", "nop", "test", "nop", "hlm", "test",
                            "hlm", "test", "xyz", "xyz", "test", "xyz", "nop", "xyz"),
                 "type" = c("1", "2", "1", "2", "2", "1", "1", "2",
                            "1", "1", "2", "2", "2", "3", "1", "1"))

I want to 1) group by participant and group, 2) check the type of each item which has value == "test", then 3) code a new column test_type which spreads the type of each "test" across all rows within the same participant/group combination.

The final result should look like this:

df$test_type <- c("1", "1", "1", "1", "2", "2", "2", "2",
                   "1", "1", "2", "2", "2", "2", "2", "2")

Any tips?

CodePudding user response:

An option is to subset the 'type' that corresponds to 'test' in `value' column after grouping by 'participant' and 'group'

library(dplyr)
df %>% 
   group_by(participant, group) %>% 
   mutate(test_type = type[value %in% 'test']) %>%
   ungroup

-output

# A tibble: 16 × 6
   participant group item  value type  test_type
   <chr>       <chr> <chr> <chr> <chr> <chr>    
 1 1           1111  a     xyz   1     1        
 2 1           1111  b     hlm   2     1        
 3 1           1111  c     test  1     1        
 4 1           1111  d     nop   2     1        
 5 1           1113  e     test  2     2        
 6 1           1113  f     nop   1     2        
 7 1           1113  g     hlm   1     2        
 8 1           1114  h     test  2     2        
 9 2           1111  i     hlm   1     1        
10 2           1111  j     test  1     1        
11 2           1113  k     xyz   2     2        
12 2           1113  l     xyz   2     2        
13 2           1113  m     test  2     2        
14 2           1113  n     xyz   3     2        
15 2           1113  o     nop   1     2        
16 2           1113  p     xyz   1     2           
  • Related