使用R将列表中具有不同日期的数据帧转换为单个数据帧

问题描述 投票:1回答:1

我想将列表中的表格变成单个数据帧。我这里有数据

datex <- c("2018/01/01","2018/01/02","2018/01/03")
x1 <- c(101,102,103); varx1 <- data.frame(x1,datex)
datex <- c("2018/01/01","2018/01/02","2018/01/03","2018/01/04","2018/01/05")
x2 <- c(10,11,12,13,14); varx2 <- data.frame(x2,datex)
datex <- c("2018/01/01")
x3 <- c(1000); varx3 <- data.frame(x3,datex)
combination <- list(varx1,varx2,varx3)
combination

我希望得到像这样的“NULL”或“NA”的结果

datex <- c("2018/01/01","2018/01/02","2018/01/03","2018/01/04","2018/01/05")
x1 <- c(101,102,103,"NULL","NULL")
x2 <- c(10,11,12,13,14)
x3 <- c(1000,"NULL","NULL","NULL","NULL")
answer <- data.frame(datex, x1,x2,x3)
answer

需要帮助!

r dplyr data.table reshape reshape2
1个回答
4
投票

我们可以使用来自Reducemergebase R。缺少的值将是NA而不是NULL

Reduce(function(...) merge(..., by = 'datex', all = TRUE), combination)
#       datex  x1 x2   x3
#1 2018/01/01 101 10 1000
#2 2018/01/02 102 11   NA
#3 2018/01/03 103 12   NA
#4 2018/01/04  NA 13   NA
#5 2018/01/05  NA 14   NA

tidyverse类似的选择将是

library(tidyverse)
combination %>%
      reduce(full_join, by = 'datex') %>%
      select(datex, everything())
#      datex  x1 x2   x3
#1 2018/01/01 101 10 1000
#2 2018/01/02 102 11   NA
#3 2018/01/03 103 12   NA
#4 2018/01/04  NA 13   NA
#5 2018/01/05  NA 14   NA

如果我们真的需要NULL,它可以放在list(不推荐)

combination %>%
      reduce(full_join, by = 'datex') %>%
      select(datex, everything()) %>%
      mutate_at(vars(matches('x\\d+')), funs(replace(., is.na(.), list(NULL))))
#    datex   x1 x2   x3
#1 2018/01/01  101 10 1000    
#2 2018/01/02  102 11 NULL
#3 2018/01/03  103 12 NULL
#4 2018/01/04 NULL 13 NULL
#5 2018/01/05 NULL 14 NULL
© www.soinside.com 2019 - 2024. All rights reserved.