【问题标题】:Append column name to the beginning of values separated by an underscore将列名附加到由下划线分隔的值的开头
【发布时间】:2021-02-07 20:20:21
【问题描述】:

如何将列名附加到列中每个值的开头,用“_”分隔,跳过第一列(或者,等效地,选择第二列和第三列)?

multiple=data.frame(id=c(1:6), 
     status=c("good", "bad", "ok", "ok", "good", "bad"), 
     breakfast=c("eggs", "sausage", "eggs", "sausage", "sausage", "eggs"))
# Desired:
#id status breakfast
#1  status_good breakfast_eggs
#2  status_bad  breakfast_sausage
#3  status_ok   breakfast_eggs
#4  status_ok   breakfast_sausage
#5  status_good breakfast_sausage
#6  status_bad  breakfast_eggs

【问题讨论】:

    标签: r dataframe dplyr stringr


    【解决方案1】:

    这是一个带有tidyverse 的选项,我们循环across 列并粘贴相应的列名(cur_column()

    library(dplyr)
    library(stringr)
    multiple %>%
        mutate(across(c(status, breakfast), ~ str_c(cur_column(), "_", .)))
    

    -输出

    #  id      status         breakfast
    #1  1 status_good    breakfast_eggs
    #2  2  status_bad breakfast_sausage
    #3  3   status_ok    breakfast_eggs
    #4  4   status_ok breakfast_sausage
    #5  5 status_good breakfast_sausage
    #6  6  status_bad    breakfast_eggs
    

    【讨论】:

      【解决方案2】:

      在base R中,我们可以使用Map

      multiple[-1] <- Map(function(x, y) paste(x, y, sep = '_'), 
                           names(multiple)[-1], multiple[-1])
      

      或者用purrrimap_dfc

      multiple[-1] <- purrr::imap_dfc(multiple[-1], ~paste(.y, .x, sep = '_'))
      multiple
      
      #  id      status         breakfast
      #1  1 status_good    breakfast_eggs
      #2  2  status_bad breakfast_sausage
      #3  3   status_ok    breakfast_eggs
      #4  4   status_ok breakfast_sausage
      #5  5 status_good breakfast_sausage
      #6  6  status_bad    breakfast_eggs
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-04
        • 2020-04-30
        • 2014-03-16
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多