【问题标题】:How create new column an add column names by selected row in r如何创建新列并通过 r 中的选定行添加列名
【发布时间】:2020-10-05 01:06:52
【问题描述】:
a<-c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE)
b<-c(TRUE,FALSE,TRUE,FALSE,FALSE,FALSE)
c<-c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE)
costumer<-c("one","two","three","four","five","six")
df<-data.frame(costumer,a,b,c)

这是一个示例代码。看起来像这样打印:

  costumer     a     b     c 
1      one  TRUE  TRUE  TRUE  
2      two FALSE FALSE  TRUE 
3    three  TRUE  TRUE  TRUE 
4     four FALSE FALSE FALSE 
5     five  TRUE FALSE  TRUE 
6      six FALSE FALSE FALSE

我想为数据中的每一行创建一个新列 df$items,其中仅包含 TRUE 的列名。像这样的:

  costumer     a     b     c items
1      one  TRUE  TRUE  TRUE  a,b,c
2      two FALSE FALSE  TRUE  c
3    three  TRUE  TRUE  TRUE  a,b,c
4     four FALSE FALSE FALSE 
5     five  TRUE FALSE  TRUE 
6      six FALSE FALSE FALSE

我想过使用apply函数或使用which来选择索引,但想不通。谁能帮帮我?

【问题讨论】:

    标签: r dataframe dplyr data-manipulation data-wrangling


    【解决方案1】:
    df$items = apply(df[2:4], 1, function(x) toString(names(df[2:4])[x]))
    df
    #   custumer     a     b     c   items
    # 1      one  TRUE  TRUE  TRUE a, b, c
    # 2      two FALSE FALSE  TRUE       c
    # 3    three  TRUE  TRUE  TRUE a, b, c
    # 4     four FALSE FALSE FALSE        
    # 5     five  TRUE FALSE  TRUE    a, c
    # 6      six FALSE FALSE FALSE       
    

    【讨论】:

      【解决方案2】:

      你可以使用

      df$items <- apply(df, 1, function(x) toString(names(df)[which(x == TRUE)]))
      

      输出

      #   custumer     a     b     c   items
      # 1      one  TRUE  TRUE  TRUE a, b, c
      # 2      two FALSE FALSE  TRUE       c
      # 3    three  TRUE  TRUE  TRUE a, b, c
      # 4     four FALSE FALSE FALSE        
      # 5     five  TRUE FALSE  TRUE    a, c
      # 6      six FALSE FALSE FALSE        
      

      【讨论】:

        【解决方案3】:
        df$items <- apply(df, 1, function(x) paste0(names(df)[x == TRUE], collapse = ","))
        df
          custumer     a     b     c items
        1      one  TRUE  TRUE  TRUE a,b,c
        2      two FALSE FALSE  TRUE     c
        3    three  TRUE  TRUE  TRUE a,b,c
        4     four FALSE FALSE FALSE      
        5     five  TRUE FALSE  TRUE   a,c
        6      six FALSE FALSE FALSE      
        

        【讨论】:

          【解决方案4】:

          我们可以使用pivot_longerreshape 为'long'格式,然后通过paste进行分组

          library(dplyr)
          library(tidyr)
          library(stringr)
          df %>%
              pivot_longer(cols = a:c) %>%
              group_by(costumer) %>% 
              summarise(items = toString(name[value])) %>% 
              left_join(df)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-07-19
            • 1970-01-01
            • 1970-01-01
            • 2021-06-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多