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

前端 未结 1 1526
[愿得一人]
[愿得一人] 2021-01-25 09:20

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

相关标签:
1条回答
  • 2021-01-25 10:07

    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)
    
    0 讨论(0)
提交回复
热议问题