I have a dataframe called imp2
(with about 6,000 rows) for which there are 9 columns labeled \'savres1\'...\'savres9\'
. Values in each of these columns
We can use max.col
i1 <- grep("^savre", names(df1))
transform(df1, savre = (max.col(df1[i1], "first"))* !!rowSums(df1[i1]))
# col1 col2 savres1 savres2 savres3 savres4 savre
#1 1 2 0 0 0 0 0
#2 2 3 0 0 0 0 0
#3 3 4 1 0 0 0 1
#4 4 5 0 0 1 0 3
df1 <- data.frame(col1 = 1:4, col2 = 2:5, savres1 = c(0, 0, 1,0),
savres2 = 0, savres3 = c(0, 0, 0, 1), savres4 = 0)