I am trying to create a new variable (var5) that takes the value from one of the other numeric variables in the dataframe (var1, var2 or var3), based on the level of a factor variable (var4)
variables=data.frame(var1=c(2,3,4,5), var2=c(20,30,40,50), var3=c(200,300,400,500), var4=c('var1','var2','var3','var1'))
variables
var1 var2 var3 var4
1 2 20 200 var1
2 3 30 300 var2
3 4 40 400 var3
4 5 50 500 var1
The expected result would be this:
var1 var2 var3 var4 var5
1 2 20 200 var1 2
2 3 30 300 var2 30
3 4 40 400 var3 400
4 5 50 500 var1 5
I could not find a way to work it out.