I have a df as below columns ID:D, and I would like to create column E. Column E should be conditionally filled by the character data in columns A, B and C based on the instruction from column D.
| ID | A | B | C | D | E |
|---|---|---|---|---|---|
| t1 | tsg | tlm | NA | 1 | tsg |
| t2 | tsg | tlm | NA | 2 | tlm |
| t3 | tfp | tsl | tgg | 3 | tgg |
| t4 | tsg | tfp | NA | 2 | tfp |
| t5 | tlm | NA | NA | 1 | tlm |
| t6 | tgg | tlm | NA | 1 | tgg |
I have been trying to do it like this but it won't work and I can't understand why.
df$E[df$D == 1 ] <- df$A
df$E[df$D == 2 ] <- df$B
df$E[df$D == 3 ] <- df$C
If the solution could be in base R I'd also be very grateful!