On 26/10/2015 6:24 AM, Lorenz, Jennifer wrote:
> Hi,
> 
> I  have a question regarding the creation of new variables on the basis of 
> existing ones in R.
> 
> I have two variables containing information on parents' educational degree 
> (e.g. 1 'high school degree', 2 'college degree', etc.). I would like to 
> create a new variable for 'parents' highest educational degree', i.e. if 
> variable1 (father's degree) is higher than variable2 (mother's degree) than 
> the new variable (variable3) should take on the value of variable1, if not, 
> than variable3 should take on the value of variable2.
> 
> I usually use SPSS for data manipulation, there I would code variable3 as 
> follows:
> COMPUTE variable3= 0.
> IF variable1 > variable2 variable3= variable1.
> IF variable1 <= variable2 variable3= variable2.
> 
> The closest I came to that in R was with this code:
> data$variable3 <- 0
> data$variable3[data$variable1 > data$variable2]<-data$variable1
> data$variable3[data$variable1 <= data$variable2]<-data$variable2
> 
> I also tried:
> data$variable3 <- ifelse(data$variable1 > data$variable2), data$variable1, 
> data$variable2)
> 
> Both didn't work.
> 
> I am not sure if my post is at all understandable (this is my first time 
> posting on R-help), but I am really hoping for some advice!

This is a good place to use the ifelse() function:

data$variable3 <- ifelse(data$variable1 > data$variable2,
                         data$variable1, data$variable2)

Duncan Murdoch

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to