【问题标题】:R: using data.table inside lapplyR:在 lapply 中使用 data.table
【发布时间】:2020-03-12 04:46:54
【问题描述】:

我有一个 data.table:

> dt
id x
1  2
2  1
2  3

要按 id 统计数据,我使用以下命令:

> dt[, .N, by = id]
id N
1  1
2  2

但我有这些数据表的完整列表,我想对它们中的每一个都执行上述操作。在这种情况下我怎么称呼 lapply ?即:

lapply(list_of_dts, ??)

【问题讨论】:

    标签: r data.table lapply


    【解决方案1】:

    您可以对 data.table 列表使用相同的命令

    library(data.table)
    
    lapply(list_of_dt, function(dt) dt[, .N, by = id])
    
    #[[1]]
    #   id N
    #1:  1 1
    #2:  2 2
    
    #[[2]]
    #   id N
    #1:  1 1
    #2:  2 2
    

    数据

    list_of_dt <- list(structure(list(id = c(1L, 2L, 2L), x = c(2L, 1L, 3L)), 
    class = c("data.table", "data.frame"), row.names = c(NA, -3L), 
    .internal.selfref = <pointer: 0x10400a0e0>), 
    structure(list(id = c(1L, 2L, 2L), x = c(2L, 1L, 3L)), class = c("data.table", 
    "data.frame"), row.names = c(NA, -3L), .internal.selfref = <pointer: 0x10400a0e0>))
    

    【讨论】:

    • 这个答案是干净的+1。另一个不太干净的简写是lapply(list_of_dt, '[', , .N, by = id)
    • 我曾尝试过这样做,但无法使语法正常工作。谢谢。
    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    相关资源
    最近更新 更多