【问题标题】:combining column of list in r在r中组合列表的列
【发布时间】:2018-11-07 19:20:33
【问题描述】:

我有数据,第一列是列表列,第二列是相应的数字。我想根据第二列的数量组合第一列中的实体。这是示例;第一列是课程列表,第二列是对应的学期:

df:

course  sem
math00     1
phys1      2
NA         3
eng00      4
c("math00","Geo00")   1
math02         2
NA         3

结果是:

course                         semester
c("math00","math00","Geo00")        1
c("phys1","math02")                 2
NA                                  3
eng00                               4

如何在 R 中做到这一点?

【问题讨论】:

    标签: r list multiple-columns


    【解决方案1】:

    假设“学期”列为list,按“学期”分组,unlist“课程”,然后将summarise分组为list

    library(tidyverse)
    df %>%
       group_by(semester) %>%
       summarise(course = list(unique(unlist(course))))
    

    或者使用aggregate from base R

    aggregate(df['course'], df['semester'], FUN = function(x) list(unique(unlist(x))))
    #   semester        course
    #1        1 math00, Geo00
    #2        2 phys1, math02
    #3        3            NA
    #4        4         eng00
    

    数据

    df <- data.frame(course = I(list('math00', 'phys1', NA, 'eng00', 
        c('math00', 'Geo00'), 'math02',NA)), semester = c(1, 2, 3, 4, 1, 2, 3))
    

    【讨论】:

    • 使用聚合给我一个错误:invalid type (list) for variable 'course'.class(df$course) gives [1] "list"。问题出在哪里?
    • @Cina 早些时候我没有测试它。 aggregateformula 方法似乎与list 有问题
    • 谢谢@akrun。一个简单的问题;我想添加更多列,例如df %&gt;% group_by(semester) %&gt;% summarise(course = list(unique(unlist(course))) summarise(course2 = list(unique(unlist(course2))))。如何将第二个命令添加到前一个命令? (course2 代码不起作用)
    • @Cina 如果我理解,您可以使用summarise_at 并将列指定为“课程”、“课程2”。即df %&gt;% group_by(semester) %&gt;% summarise_at(vars(matches('course')), funs(list(unique(unlist(.)))))
    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多