如何 match/merge 来自 R 中两个不同文件的数据?

How to match/merge data from two different files in R?

我有两个文件(file1.csv 和 file2.csv)。如下所示,文件 1 包含两列日期和具有 365 个观测值(全年)的变量 x1。文件 2 包含列日期作为文件 1 和许多其他变量。我只对只有 24 个观察值(每个月 2 个观察值)的变量 x45 感兴趣。

文件 1

date     x1
1/01/2005   33
2/01/2005   24
3/01/2005    72
31/12/2005   52

文件 2

date     x2      x3     x45
1/01/2005               115
5/02/2005                125
13/04/2005               127
31/12/2005               138

所以我想将列 x45 添加到 file1.csv 看起来像

date    x1    x45
1/01/2005   33  115
2/01/2005   24    NA
3/01/2005    72   NA
31/12/2005   52           138

我试过使用

file1= read.csv("D:/file1.csv")
file2= read.csv("D:/file2.csv")
file3 = merge(file1, file2)

但是,文件 3 只有 24 行(观察结果)并且忽略了文件 1 中的其余观察结果。

如能提供任何有助于获得上述结果的帮助,我们将不胜感激。

你可以试试left_join

library(dplyr)
left_join(df1, df2[c('date', 'x45')], by='date')
#         date x1 x45
#1  1/01/2005 33 115
#2  2/01/2005 24  NA
#3  3/01/2005 72  NA
#4 31/12/2005 52 138

或使用merge

merge(df1, df2[c('date', 'x45')], all.x=TRUE)
#       date x1 x45
#1  1/01/2005 33 115
#2  2/01/2005 24  NA
#3  3/01/2005 72  NA
#4 31/12/2005 52 138

更新

dplyrleft_joinplyrjoin保持原来的顺序。如果您需要在 merge 中保持顺序,一种选择是在 "df1" 中创建一个 "indx",在 merge 之后,可以使用 [=37] 保留原始顺序=]

df1$indx <- 1:nrow(df1)
 merge(df1, df2[c('date', 'x45')], all.x=TRUE)[order(df1$indx),-3]
    date x1 x45
 #1  1/01/2005 33 115
 #2  2/01/2005 24  NA
 #3  3/01/2005 72  NA
 #4 31/12/2005 52 138

或使用 plyr

中的 join
library(plyr)
join(df1, df2[c('date', 'x45')], by='date', type='left')

数据

df1 <- structure(list(date = c("1/01/2005", "2/01/2005", "3/01/2005", 
"31/12/2005"), x1 = c(33L, 24L, 72L, 52L)), .Names = c("date", 
"x1"), class = "data.frame", row.names = c(NA, -4L))

df2 <- structure(list(date = c("1/01/2005", "5/02/2005", "13/04/2005", 
"31/12/2005"), x2 = c(NA, NA, NA, NA), x3 = c(NA, NA, NA, NA), 
x45 = c(115L, 125L, 127L, 138L)), .Names = c("date", "x2", 
 "x3", "x45"), class = "data.frame", row.names = c(NA, -4L))

以下也可以工作,不需要包,也不会改变 df1 中行的原始顺序:

df1
#        date x1
#2  1/01/2005 33
#3  2/01/2005 24
#4  3/01/2005 72
#5 31/12/2005 52
df2
#        date x45
#1  1/01/2005  33
#2  2/01/2005  24
#3  3/01/2005  72
#4 31/12/2005  52

df1$x45 <- df2$x45[match(df1$date, df2$date)]

df1
#        date x1 x45
#2  1/01/2005 33  33
#3  2/01/2005 24  24
#4  3/01/2005 72  72
#5 31/12/2005 52  52

为了完整起见,您可以使用 data.table 程序包

通过引用(不使用 <-)非常快速地加入和更新 file1
library(data.table)
setkey(setDT(file1), date)[file2, x45 := i.x45]
file1
#          date x1 x45
# 1:  1/01/2005 33 115
# 2:  2/01/2005 24  NA
# 3:  3/01/2005 72  NA
# 4: 31/12/2005 52 138

在这里,您通过 date 列键入 file1 并在 file2 上执行二进制连接,同时仅拉取 x45