合并数据框和列表

时间:2014-03-17 16:18:12

标签: r list merge dataframe

我有一个日期数据框,我希望与具有不同行数(3或4)的列表合并。我想将数据框的第一个日期与列表的所有元素(日期)合并。例如,df1中的前两个日期与列表的前两个元素(bc)合并,我会得到以下内容:

date        date1       id
1992-09-26  1992-09-05  1
1992-09-26  1992-09-12  1
1992-09-26  1992-09-19  1
1992-09-27  1992-09-06  2
1992-09-27  1992-09-13  2
1992-09-27  1992-09-20  2

我该怎么做?我搜索了这个论坛,没有找到类似的问题或类似的解决方案。

df1 <- structure(c(8304, 8305, 8306, 8307, 8308, 8309, 8310, 8311, 8312, 
8313, 8314), class = "Date")

mylist <- list(structure(c(8283, 8290, 8297), class = "Date"), structure(c(8284, 
8291, 8298), class = "Date"), structure(c(8285, 8292, 8299), class = "Date"), 
    structure(c(8279, 8286, 8293, 8300), class = "Date"), structure(c(8280, 
    8287, 8294, 8301), class = "Date"), structure(c(8316, 8323, 
    8330, 8337), class = "Date"), structure(c(8317, 8324, 8331, 
    8338), class = "Date"), structure(c(8318, 8325, 8332, 8339
    ), class = "Date"), structure(c(8319, 8326, 8333), class = "Date"), 
    structure(c(8320, 8327, 8334), class = "Date"), structure(c(8321, 
    8328, 8335), class = "Date"))

2 个答案:

答案 0 :(得分:1)

非常不优雅,但它有效:

df <- as.data.frame(do.call("rbind", mapply(function(x,y) cbind(date=x, date1=y, id=which(df1==x)), df1, mylist)))

class(df[,1]) <- "Date"
class(df[,2]) <- "Date"

head(df)
        date      date1 id
1 1992-09-26 1992-09-05  1
2 1992-09-26 1992-09-12  1
3 1992-09-26 1992-09-19  1
4 1992-09-27 1992-09-06  2
5 1992-09-27 1992-09-13  2
6 1992-09-27 1992-09-20  2

答案 1 :(得分:0)

听起来您只是在寻找repunlist,如下所示:

A <- sapply(mylist, length)
out <- data.frame(date = rep(df1, A),
                  date1 = unlist(mylist),
                  id = rep(seq_along(A), A))
head(out)
#         date date1 id
# 1 1992-09-26  8283  1
# 2 1992-09-26  8290  1
# 3 1992-09-26  8297  1
# 4 1992-09-27  8284  2
# 5 1992-09-27  8291  2
# 6 1992-09-27  8298  2
tail(out)
#          date date1 id
# 33 1992-10-05  8320 10
# 34 1992-10-05  8327 10
# 35 1992-10-05  8334 10
# 36 1992-10-06  8321 11
# 37 1992-10-06  8328 11
# 38 1992-10-06  8335 11

您也可以使用data.table

library(data.table)
DT <- data.table(date = df1, date1 = mylist, key = "date")
DT[, id := 1:nrow(DT)]
DT[, as.IDate(unlist(date1), origin = "1970-01-01"), by = list(date, id)]