R - create new column dataframe based on index of value match with existing column

依然范特西╮ 提交于 2019-12-02 03:36:54

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

data

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!