I have a simple example data frame with two data columns (data1 and data2) and two grouping variables (Measure 1 and 2). Measure 1 and 2 have missing data NA.
d <- data.frame(Measure1 = 1:2, Measure2 = 3:4, data1 = 1:10, data2 = 11:20)
d$Measure1[4]=NA
d$Measure2[8]=NA
d
Measure1 Measure2 data1 data2
1 1 3 1 11
2 2 4 2 12
3 1 3 3 13
4 NA 4 4 14
5 1 3 5 15
6 2 4 6 16
7 1 3 7 17
8 2 NA 8 18
9 1 3 9 19
10 2 4 10 20
I want to create a new variable (d$new) that contains data1, but only for rows where Measure1 equals 1. I tried this and get the following error:
d$new[d$Measure1 == 1] = d$data1[d$Measure1 == 1]
Error in d$new[d$Measure1 == 1] = d$data1[d$Measure1 == 1] : NAs are not allowed in subscripted assignments
Next I would like to add to d$new the data from data2 only for rows where Measure2 equals 4. However, the missing data in Measure1 and Measure2 is causing problems in subsetting the data and assigning it to a new variable. I can think of some overly complicated solutions, but I'm sure there's an easy way I'm not thinking of. Thanks for the help!