1
votes

I have a small problem, or acctually kind of large. I have a dataset with 3 variables that I use atm, lets call them var1, var2 and var3. In total I have over 3000 observations with NA values in every variable.

var1=age_1, var2=Yes/No and var3=age_2

What I want to do is if var2="Yes" the value from var1 should be coopied into var3. I have done it in this way:

var3[var2=="Yes"]<-var1

but I get the error message:

Error in var3[var2 == "Yes"] <-var1 :

NAs are not allowed in subscripted assignments

Someone has a quick solution how I can solve this?

2
var3 <- ifelse(test = (var2 == 'YES'), var1, var3)hd1

2 Answers

3
votes

You can try

var3 <- ifelse(var2 == "Yes", var1, var3)
2
votes

The error sounds like you have NA values in var2. You can test to see if sum(is.na(var))>0 So if you have missing values R doesn't want to guess if missing is the same as "Yes" or "No" so you get the error.

Also, by only indexing one side of the assignment, you're not necessarily matching up values across rows. So even in you fix your NA values, you'd likley get the number of items to replace is not a multiple of replacement length error.

One trick is to use which to remove NA values form the logical indexes and transform them into numeric indices. Then once you know the rows you want to replace, you can use the same index on both sides of the assignment.

idx <- which(var2=="Yes")
var3[idx] <- var1[idx]

or you can use the ifelse function which makes all these steps much easier

var3<-ifelse(var2=="Yes", var1, var3)