samedi 29 octobre 2016

Choose column name of the first column which fits certain logical test

Input

Hi all, I have following input:

id <- c("a", "b", "c", "d")
target <- seq(from = 100, to = 400, length.out = 4)
a <- c(300, 304, 100, 405)
b <- c(300, 104, 100, 405)
c <- c(85, 304, 500, 405)
df <- as.data.frame(cbind(id, target, a, b, c))

I would like to add a new column "column" which indicates per row, which of the columns "a", "b", "c" would be the first column with a value smaller than the target solution. The requested output looks like this:

Required Output

df$column <- c("c", "b", "a", "NA")
df

I thought about a concenated if check per row and apply this to all rows with the apply function. However the abc columns are quite long (round 20, therefore a loop would be required) and the number of rows are about 4.000. Does anybody have an idea on how to solve it? Thanks! Nils

Aucun commentaire:

Enregistrer un commentaire