[R] Combine two variables

Simon Kiss sjkiss at gmail.com
Tue Sep 11 16:57:10 CEST 2012


Hi:
I have two variables in a data frame that are the results of a wording experiment in a survey. I'd like to create a third variable that combines the two variables.  Recode doesn't seem to work, because it just recodes the first variable into the third, then recodes the second variable into the third, overwriting the first recode. I can do this with a rather elaborate indexing process, subsetting the first column and then copying the data into the second etc. But I'm looking for a cleaner way to do this. The data frame looks like this.


df<-data.frame(var1=sample(c('a','b','c',NA),replace=TRUE, size=100), var2=sample(c('a','b','c',NA),replace=TRUE,size=100))

df<-subset(df, !is.na(var1) |!is.na(var2))

As you can see, if one variable has an NA, then the other variable has a valid value, so how do I just combine the two variables into one?
Thank you for your assistance.
Simon Kiss



More information about the R-help mailing list