【问题标题】:add new column to dataframe by referencing name of existing columns通过引用现有列的名称将新列添加到数据框
【发布时间】:2018-05-05 13:39:33
【问题描述】:

我有一个这种形式的数据框:

df <- data.frame(abc = c(1, 0, 3, 2, 0), 
                 foo = c(0, 4, 2, 1, 0),
                 glorx = c(0, 0, 0, 1, 2))

在这里,列名是字符串,数据框中的值是我想将该字符串连接到新数据列中的次数。我想创建的新列将是所有现有列的串联,每个列名根据数据重复。

例如,我想创建这个新列并将其添加到数据框中。

new_col <- c('abc', 'foofoofoofoo', 'abcabcabcfoofoo', 'abcabcfooglorx', 'glorxglorx')
also_acceptable <- c('abc', 'foofoofoofoo', 'abcfooabcfooabc', 'abcfooglorxabc', 'glorxglorx')

df %>% mutate(new_col = new_col, also_acceptable = also_acceptable)

连接的顺序无关紧要。我遇到的核心问题是在构建purrr::map()dplyr::mutate() 函数来构建新列时,我不知道如何逐行引用列的名称。因此,我不确定如何以编程方式构建这个新列。

(这里的核心应用是化学式的组合构造,以防有人想知道我为什么需要这样的东西。)

【问题讨论】:

    标签: r string dataframe dplyr tidyverse


    【解决方案1】:

    这是一个使用Mapstrrep 的选项:

    mutate(df, new_col = do.call(paste, c(sep="", Map(strrep, names(df), df))))
    
    #  abc foo glorx         new_col
    #1   1   0     0             abc
    #2   0   4     0    foofoofoofoo
    #3   3   2     0 abcabcabcfoofoo
    #4   2   1     1  abcabcfooglorx
    #5   0   0     2      glorxglorx
    

    或者像@thelatemail 的评论那样更简单的版本:

    df %>% mutate(new_col = do.call(paste0, Map(strrep, names(.), .)))
    

    Map 给出的列表如下:

    Map(strrep, names(df), df) %>% as.tibble()
    
    # A tibble: 5 x 3
    #        abc          foo      glorx
    #      <chr>        <chr>      <chr>
    #1       abc                        
    #2           foofoofoofoo           
    #3 abcabcabc       foofoo           
    #4    abcabc          foo      glorx
    #5                        glorxglorx
    

    使用do.call(paste, ...) 逐行粘贴字符串。

    【讨论】:

    • 不错,但您可以使用 paste0 - do.call(paste0, Map(strrep, names(df), df)) 进行简化
    • @thelatemail 没错。这次我得到paste0。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2017-09-13
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多