I want to create a new variable called N1 based on three existing variables (resp, exp.1, exp.2) in R.
df <- data.frame(
resp = c(1, 2, 4, 3, 5, 7 ),
exp.1 = c(0, 0.24, 1, 1.5, 0, 0.4),
exp.2 = c(1, 1, 0, 0, 0.3, 0.2)
)
df resp exp.1 exp.2
1 1 0 1
2 2 0.24 1
3 2 1 0
4 4 1.5 0
5 5 0 0.3
6 7 0.4 0.2
I want to make a new variable N1 like this:
when resp >4, extracting values from exp.1
when resp <4, extracting values from exp.2
when resp == 4, making it missing values.
The desired outcome is:
df resp exp.1 exp.2 N1
1 1 0 1 1
2 2 0.24 1 1
3 4 1 0 NA
4 3 1.5 0 0
5 5 0 0.3 0
6 7 0.4 0.2 0.4
I tried my best using mutate() or car::recode() but it does not work. Any clues?