I'm trying to clean up a data frame and I would like to replace NAs in one column, with a corresponding value from another column. I would also like to do this for multiple columns at once.
Example Data Frame.
set.seed(123)
dates <- seq(as.Date("2016-01-01"), by = "day", length = 10)
names <- rep(c("John Doe", "Jane Smith"), each = 5)
var1_group <- runif(10)
var2_group <- runif(10)
var1_person <- runif(10)
var2_person <- runif(10)
myDF <- data.frame(names, var1_group, var2_group, var1_person, var2_person)
myDF <- cbind(dates, myDF)
After some manipulations using dplyr...
myDF <- myDF %>% mutate_each(funs(lag), contains("group"))
myDF <- myDF %>% group_by(names) %>% mutate_each(funs(lag), contains("person"))
I get a bunch of NAs...
dates names var1_group var2_group var1_person var2_person
1 2016-01-01 John Doe NA NA NA NA
2 2016-01-02 John Doe 0.2875775 0.95683335 0.8895393 0.9630242
3 2016-01-03 John Doe 0.7883051 0.45333416 0.6928034 0.9022990
4 2016-01-04 John Doe 0.4089769 0.67757064 0.6405068 0.6907053
5 2016-01-05 John Doe 0.8830174 0.57263340 0.9942698 0.7954674
6 2016-01-06 Jane Smith 0.9404673 0.10292468 NA NA
7 2016-01-07 Jane Smith 0.0455565 0.89982497 0.7085305 0.4777960
8 2016-01-08 Jane Smith 0.5281055 0.24608773 0.5440660 0.7584595
9 2016-01-09 Jane Smith 0.8924190 0.04205953 0.5941420 0.2164079
10 2016-01-10 Jane Smith 0.5514350 0.32792072 0.2891597 0.3181810
What I would like to do now, is replace the NAs from *_person columns with the corresponding value from the *_group column. (See row 6)
dates names var1_group var2_group var1_person var2_person
1 2016-01-01 John Doe NA NA NA NA
2 2016-01-02 John Doe 0.2875775 0.95683335 0.8895393 0.9630242
3 2016-01-03 John Doe 0.7883051 0.45333416 0.6928034 0.9022990
4 2016-01-04 John Doe 0.4089769 0.67757064 0.6405068 0.6907053
5 2016-01-05 John Doe 0.8830174 0.57263340 0.9942698 0.7954674
6 2016-01-06 Jane Smith 0.9404673 0.10292468 0.9404673 0.1029246
7 2016-01-07 Jane Smith 0.0455565 0.89982497 0.7085305 0.4777960
8 2016-01-08 Jane Smith 0.5281055 0.24608773 0.5440660 0.7584595
9 2016-01-09 Jane Smith 0.8924190 0.04205953 0.5941420 0.2164079
10 2016-01-10 Jane Smith 0.5514350 0.32792072 0.2891597 0.3181810
This works for one column...
myDF$var1_person <- ifelse(is.na(myDF$var1_person), myDF$var1_group, myDF$var1_person)
But I'd like to do it for all the columns at once. In my actual data frame, each group is around 20 columns. I've tried a bunch of other stuff, but I don't want to clutter this post with my nonsense.
*Bonus points if you can get the code to match for n variables based on column prefix.
var1_group > var1_person
var2_group > var2_person
...
varn_group > varn_person