How can I go through a vector in R Dataframe

后端 未结 2 595
野性不改
野性不改 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:42

    An option would be to gather the data into 'long' format, filter the rows with 'Y', grouped by 'Name', paste the elements in 'key' (str_c) and left_join with the original dataset

    library(tidyverse)
    df1 %>%
       gather(key, val, -Name) %>% 
       filter(val == 'Y') %>% 
       group_by(Name) %>% 
       summarise(Sports = str_c(key, collapse= ' and ')) %>%
       left_join(df1) %>%
       select(names(df1), "Sports")
    # A tibble: 3 x 5
    #  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
    

    data

    df1 <- structure(list(Name = c("A", "B", "C"), Cricket = c("Y", "N", 
    "Y"), Football = c("Y", "Y", "N"), Swimming = c("N", "N", "Y"
    )), class = "data.frame", row.names = c(NA, -3L))
    

提交回复
热议问题