代码之家  ›  专栏  ›  技术社区  ›  road_to_quantdom

如何使用NA上的特定条件合并多个数据表

  •  1
  • road_to_quantdom  · 技术社区  · 8 年前

    我有 data.table 采用此格式的:

    dt1 <- data.table(row_names=1:5, perf=c(2,NA,NA,3,NA), ticker=rep("aa",5))
    dt2 <- data.table(row_names=1:5, perf=c(NA,1,2,5,NA), ticker=rep("aapl",5))
    
       row_names perf ticker
    1:         1    2     aa
    2:         2   NA     aa
    3:         3   NA     aa
    4:         4    3     aa
    5:         5   NA     aa  
    
       row_names perf ticker
    1:         1   NA   aapl
    2:         2    1   aapl
    3:         3    2   aapl
    4:         4    5   aapl
    5:         5   NA   aapl  
    

    我有 N ,并希望将其联接,以便 perf 。但是,如果 NA 其中一个数据表存在值。在上述情况下,我希望得到结果数据。表格:

    > res <- data.table(row_names=1:5,perf=c(2,1,2,4,NA),tickers=c("aa","aapl","aapl","aa,aapl",NA))
    > res
       row_names perf tickers
    1:         1    2      aa
    2:         2    1    aapl
    3:         3    2    aapl
    4:         4    4 aa,aapl
    5:         5   NA      NA
    

    我知道我可以这样做 不适用 已删除:

    rbind(dt1,dt2)[,list("perf"=mean(perf,na.rm=T)),by=row_names]

       row_names perf
    1:         1    2
    2:         2    1
    3:         3    2
    4:         4    4
    5:         5  NaN
    

    我该如何为 tickers 列根据冲突的 不适用 同时,正在rbinding所有 data tables 执行 mean 作用非常感谢。

    1 回复  |  直到 8 年前
        1
  •  4
  •   Jaap    8 年前

    使用:

    res <- rbind(dt1,dt2)[, .(perf = mean(perf, na.rm = TRUE),
                              tickers = toString(ticker[!is.na(perf)]))
                          , by = row_names]
    

    提供:

    > res
       row_names perf  tickers
    1:         1    2       aa
    2:         2    1     aapl
    3:         3    2     aapl
    4:         4    4 aa, aapl
    5:         5  NaN
    

    而不是 toString 您也可以使用 paste paste0 使用参数 collapse = ','


    根据@Frank的建议,您可以将代码修改为:

    res <- rbind(dt1,dt2)[, .(perf = if (all(is.na(perf))) NA_real_ else mean(perf, na.rm = TRUE),
                              tickers = if (all(is.na(perf))) NA_character_ else toString(ticker[!is.na(perf)]))
                          , by = row_names]
    

    其中给出:

    > res
       row_names perf  tickers
    1:         1    2       aa
    2:         2    1     aapl
    3:         3    2     aapl
    4:         4    4 aa, aapl
    5:         5   NA       NA