【问题标题】:How to make a column out of a column name its value?如何使列名中的列成为其值?
【发布时间】:2020-02-06 23:05:05
【问题描述】:

我有以下数据

df<- data_frame(State= c('CA', 'IN', 'CHI'),
       Age= c(46,29,32),
       Status= c('Employed', '', 'Employed')
       )

最后,我想创建如下所示的数据:

df<- data_frame(col1= c('State-CA', 'State-IN', 'State-CHI'),
       col2= c('Age-46','Age-29','Age-32'),
       col3= c('Status-Employed', '', 'Status-Employed')
       )

用破折号连接列的名称及其值。如果缺少值,则列名不应连接到表的值。有人可以帮忙吗?提前致谢!

【问题讨论】:

    标签: r data-manipulation


    【解决方案1】:

    使用imap,只需一步。由于data.frames 被命名为list 与等于length 的列,imaplist 上循环,使用匿名函数调用 (~),得到.y 作为列名和值是.x,然后是pastestr_c

    library(purrr)
    library(stringr)
    imap_dfc(df, ~ case_when(.x ==""|is.na(.x) ~ as.character(.x), TRUE ~ str_c(.y, .x, sep='-')))
    # A tibble: 3 x 3
    #  State     Age    Status         
    #  <chr>     <chr>  <chr>          
    #1 State-CA  Age-46 Status-Employed
    #2 State-IN  Age-29 ""      
    #3 State-CHI Age-32 Status-Employed
    

    base R

    df[] <- Map(function(x, y) ifelse(x=="", x, paste(x, y, sep="-")),df, names(df))
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找的内容已在此线程上得到解答 - Insert Column Name into its Value using R。希望对您有所帮助!

      另外,这段代码应该适合你 -

      col_names <- names(df)
      for (c in col_names) {
        df[[c]] <- ifelse(df[[c]] != "", paste(c, df[[c]], sep = "-"), "")
      }
      df
      

      输出 -

       State    Age          Status
      1 State-CA Age-46 Status-Employed
      2 State-IN Age-29                
      3 State-CHI Age-32 Status-Employed
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-03
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 2018-06-18
        • 1970-01-01
        • 2021-11-16
        相关资源
        最近更新 更多