[R] Creating new variables in R

Lorenz, Jennifer jlorenz at uni-goettingen.de
Mon Oct 26 11:24:16 CET 2015


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!
Thanks!
Jen



---
Jennifer Lorenz, M.A.
Georg-August-Universität Göttingen
Sozialwissenschaftliche Fakultät
Institut für Erziehungswissenschaft
Lehrstuhl Schulpädagogik / Empirische Schulforschung

e-mail: jlorenz at uni-goettingen.de
phone: 0551-39-21411
adress: Waldweg 26, 37073 Göttingen
room: 8.106

	[[alternative HTML version deleted]]



More information about the R-help mailing list