How can I go through a vector in R Dataframe

后端 未结 2 570
野性不改
野性不改 2021-01-21 06:47

I have a dataframe that looks like this

Name   Cricket   Football   Swimming 
A      Y         Y          N
B      N         Y          N
C      Y         N              


        
2条回答
  •  借酒劲吻你
    2021-01-21 07:24

    Something like this (in base R) would do it too:

    df$Sports <- apply(df[,-1]=="Y", 1, function(r) paste(names(df)[-1][r], collapse=" and "))
    
    #  Name Cricket Football Swimming               Sports
    #1    A       Y        Y        N Cricket and Football
    #2    B       N        Y        N             Football
    #3    C       Y        N        Y Cricket and Swimming
    

提交回复
热议问题