My df is sth like this:
Item P P1 P2 P3 D1 D2 D3 pmin num NP
A 10 8 11 20 2 1 10 1 D2 11
B 10 8 11 20 2 1 10 1 D2 11
C 10 8 11 20 2 1 10 1 D2 11
D 50 40 35 70 10 15 20 10 D1 40
E 20 15 22 30 5 2 10 2 D2 22
As shown in my df above, I've first calculated D1 and D2, 'pmin' is the parallel min for D1 and D2, 'num' gives the column name(D1 or D2) corresponding to my pmin.
Now what I want is return a new column called 'NP' that gives me the corresponding values in P1 or P2 according to the pmin (by looking across the row). For example, if it says D2 in 'num', looking across the row, I return value from P2, if it says D1 in 'num', I return the value from P1.
Not sure if I explained it nicely but here's how I did for 'pmin' and 'num':
df$pmin = do.call(pmin, df[,5:6] )
df$num = apply(df[,5:6], 1,function(x) names(x)[which.min(x)])
Also in my real dataset, I have P1 through P4 and D1 through D4.
I tried sth like
ifelse( num == 'D1', P1, P2)
but it doesn't work for more than two columns (P1~P4..)
Thanks in advance!!
btw does anyone know how to use
case_when()
from library(dplyr) to get 'NP'?