1

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'?

  • 1
    Please see some guidelines [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making a reproducible question. It's difficult for us to work with data that's shown in an image, but you can post the output of calling `dput` on a representative sample. – camille Aug 16 '18 at 13:58
  • Sorry my first time using stackoverflow. I'll try to edit it again! – Valentina Sapphire Aug 16 '18 at 14:54
  • I couldn't reproduce the error mentioned. Please check the data I used with the output – akrun Aug 16 '18 at 15:13

1 Answers1

0

We can use row/column indexing to extract the elements of 'P1/P2' columns that corresponds to the 'D1', 'D2'

m1 <- cbind(seq_len(nrow(df)), match(df$num, c("D1", "D2", "D3")))
df$NP <- df[c("P1", "P2", "P3")][m1]
df$NP
#[1] 11 11 11 40 22

data

df <- structure(list(Item = c("A", "B", "C", "D", "E"), P = c(10L, 
10L, 10L, 50L, 20L), P1 = c(8L, 8L, 8L, 40L, 15L), P2 = c(11L, 
11L, 11L, 35L, 22L), P3 = c(20L, 20L, 20L, 70L, 30L), D1 = c(2L, 
2L, 2L, 10L, 5L), D2 = c(1L, 1L, 1L, 15L, 2L), D3 = c(10L, 10L, 
10L, 20L, 10L), pmin = c(1L, 1L, 1L, 10L, 2L), num = c("D2", 
"D2", "D2", "D1", "D2"), NP = c(11L, 11L, 11L, 40L, 22L)), 
 class = "data.frame", row.names = c(NA, 
-5L))
akrun
  • 874,273
  • 37
  • 540
  • 662