首页 > 解决方案 > 每行合并/连接 data.tables

问题描述

我有以下数据表,我想从所有三个数据表中制作一个数据表。

library(dplyr)
set.seed(123)

dt.Ger <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                     Germany = rnorm(365, 2, 1), check.names = FALSE)
dt.Aut <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                     Austria = rnorm(365, 4, 2), check.names = FALSE)
dt.Den <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                     Denmark = rnorm(365, 3, 1), check.names = FALSE)

dt.Ger <- dt.Ger %>%
  mutate(month = format(date, '%b'), 
         date = format(date, '%d')) %>%
  tidyr::pivot_wider(names_from = date, values_from = Germany)

dt.Aut <- dt.Aut %>%
  mutate(month = format(date, '%b'), 
         date = format(date, '%d')) %>%
  tidyr::pivot_wider(names_from = date, values_from = Austria)

dt.Den <- dt.Den %>%
  mutate(month = format(date, '%b'), 
         date = format(date, '%d')) %>%
  tidyr::pivot_wider(names_from = date, values_from = Denmark)

现在我想将所有表链接在一起,即首先dt.Ger,然后可能添加两个空行,然后追加dt.Aut,现在再次添加两个空行,最后添加dt.Den。理想情况下,如果德国是第一个标题,然后是奥地利(在之前的第二个空行中dt.Aut),然后是丹麦(在之前的第二个空行中),那就太好了dt.Den

所以我只有一张桌子作为回报。这个表应该是这样的(我只用 SnippingTool 做了,所以它只是用来解释):

在此处输入图像描述

编辑: 使用

l <- list(dt.Ger, dt.Aut, dt.Den)
l.result <- rbindlist(l)

产生于:

在此处输入图像描述

我想得到一个额外的空间/行/行(在红色部分),其中写着德国、奥地利和丹麦。

标签: rjoinmergedata.tablerows

解决方案


我仍然不确定,您要达到什么目标-对我来说,您似乎最好使用 data.tables 列表。

此外,我改用 usingdcast而不是pivot_wider这样您就可以删除tidyr/ dplyr

NA但是,这是一种在不同的 data.tables 之间插入 s 的方法,使用rbindlist

library(data.table)
set.seed(123)

dt.Ger <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                     Germany = rnorm(365, 2, 1), check.names = FALSE)
dt.Aut <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                     Austria = rnorm(365, 4, 2), check.names = FALSE)
dt.Den <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                     Denmark = rnorm(365, 3, 1), check.names = FALSE)

# or rather date  ~ month?
dt.Ger[, c("month", "date") := list(format(date, '%b'), format(date, '%d'))]
dt.Ger <- dcast(dt.Ger, month ~ date, value.var = "Germany")

dt.Aut[, c("month", "date") := list(format(date, '%b'), format(date, '%d'))]
dt.Aut <- dcast(dt.Aut, month ~ date, value.var = "Austria")

dt.Den[, c("month", "date") := list(format(date, '%b'), format(date, '%d'))]
dt.Den <- dcast(dt.Den, month ~ date, value.var = "Denmark")

# use a list of data.tables:
recommended <- list(Germany = dt.Ger, Austria = dt.Aut, Denmark = dt.Den)

DT <- rbindlist(list(data.table(month = c("", "Germany")), dt.Ger, data.table(month = c("", "Austria")), dt.Aut, data.table(month = c("", "Denmark")), dt.Den), fill = TRUE) # [, V1 := NULL]
DT[,(names(DT)):= lapply(.SD, as.character), .SDcols = names(DT)]
for (j in seq_len(ncol(DT))){
  set(DT, which(is.na(DT[[j]])), j, "")
}

print(DT)

推荐阅读