How can I go through a vector in R Dataframe

后端 未结 2 569
野性不改
野性不改 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
    
    0 讨论(0)
  • 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              
    #  <chr> <chr>   <chr>    <chr>    <chr>               
    #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))
    
    0 讨论(0)
提交回复
热议问题