Fill variable based on two variables

Hello all,

I am trying to work on this. I appreciate any help.

We have 3 persons (X,Y,Z)
We have 6 days ('NA','Mon','Tue','Wed','Thr','Fri')
For every person, We are trying to fill a column with either 'C' or 'H'. This column is called Expected_H_OR_C
If a person has one H, he/she will also have NA in the column 'Day'. The expected result for this case is that all his/her other days 'Mon' through 'Fri' will be filled with 'H'.
For all other cases, R should look how many 'C's it has and fill the rest with 'H'
Ex: If person 'Y' has 'C' for days 'Tue' and 'Fri', then the rest of his/her days
'Mon', 'Wed' and 'Thr' will fill with 'H'. If person 'W' has 'C' for his/her days, then
there is nothing to be filled.

days <- rep(c(NA, 'Mon','Tue','Wed','Thr','Fri'), 3)
person <- c(rep('X',6), rep('Y',6), rep('Z',6))
H_OR_C <- c('H',rep(NA,5),NA, 'C',rep(NA,4), NA, rep('C',2),rep(NA,3))

Expected_H_OR_C <- c('H',rep('H',5), 'H','C', rep('H',4), 'H', rep('C',2), rep('H',3))

mydata <- data.frame(days, person, HorC,Expected_H_OR_C)


Hi dsgeek, your example toward the bottom seems different to your explanation above; in your example, if there is a 'C', you want the remaining columns filled with 'C'. This is different to your data where if there is a 'C', the remaining columns are filled with a 'H'

The below should do the latter. Does this work as you expect?


mydata %>%
  mutate(Expected_H_OR_C = ifelse(, "H", as.character(H_OR_C)))

#>    days person H_OR_C Expected_H_OR_C
#> 1  <NA>      X      H               H
#> 2   Mon      X   <NA>               H
#> 3   Tue      X   <NA>               H
#> 4   Wed      X   <NA>               H
#> 5   Thr      X   <NA>               H
#> 6   Fri      X   <NA>               H
#> 7  <NA>      Y   <NA>               H
#> 8   Mon      Y      C               C
#> 9   Tue      Y   <NA>               H
#> 10  Wed      Y   <NA>               H
#> 11  Thr      Y   <NA>               H
#> 12  Fri      Y   <NA>               H
#> 13 <NA>      Z   <NA>               H
#> 14  Mon      Z      C               C
#> 15  Tue      Z      C               C
#> 16  Wed      Z   <NA>               H
#> 17  Thr      Z   <NA>               H
#> 18  Fri      Z   <NA>               H

Created on 2019-05-22 by the reprex package (v0.2.1)

1 Like

Hello mrblobby.

Your are right! I fixed the question above, but your solution works very well.
For some reason, I thought I had to include the Day variable and the Inspector.Name in my code.

Thank you for your help and best regards.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.