简体   繁体   English

合并多个 data.frames [r]

[英]merge multiple data.frames [r]

There is a list l1 of data.frames:有一个 data.frames 列表l1

head(lapply(l1,head,n=3),3)
[[1]]
   nu_pregao    pcVar
1       2371 7.224848
45      2372 2.797704
89      2373 3.947368

[[2]]
   nu_pregao    pcVar
2       2371 4.055709
46      2372 2.944882
90      2373 3.507937

[[3]]
   nu_pregao    pcVar
3       2371 4.011461
47      2372 3.679907
91      2373 4.693034

If one uses Reduce to merge them如果使用Reduce来合并它们

l2=Reduce(function(x,y) merge(x,y, by='nu_pregao'),l1)
There were 41 warnings (use warnings() to see them)

gets a sequence of warnings like this:收到一系列警告,如下所示:

1: In merge.data.frame(x, y, by = "nu_pregao") :
  column names ‘pcVar.x’, ‘pcVar.y’ are duplicated in the result

The result is ok, the only problem are the duplicated names.结果还可以,唯一的问题是名称重复。 Is there a way to avoid this?有没有办法避免这种情况?
I´ve seen question How to merge multiple data.frames and sum and average columns at the same time in R but it seems it does rbind instead of merge .我见过问题How to merge multiple data.frames and sum and average columns in the same time in R但它似乎是rbind而不是merge

What about something like this:这样的事情怎么样:

l2 <- Reduce(function(x, n) merge(x, l1[[n]], by='nu_pregao', suffixes = c("", n)),
             seq(2, length(l1)), init = l1[[1]])
l2
#>   nu_pregao    pcVar   pcVar2   pcVar3
#> 1      2371 7.224848 4.055709 4.011461
#> 2      2372 2.797704 2.944882 3.679907
#> 3      2373 3.947368 3.507937 4.693034

Final touch for names consistency:名称一致性的最后润色:

names(l2)[match("pcVar", names(l2))] <- "pcVar1"
l2
#>   nu_pregao   pcVar1   pcVar2   pcVar3
#> 1      2371 7.224848 4.055709 4.011461
#> 2      2372 2.797704 2.944882 3.679907
#> 3      2373 3.947368 3.507937 4.693034

Your data:您的数据:

l1 <- list(read.table(text = "nu_pregao    pcVar
1       2371 7.224848
45      2372 2.797704
89      2373 3.947368", header = TRUE),

read.table(text = "nu_pregao    pcVar
2       2371 4.055709
46      2372 2.944882
90      2373 3.507937", header = TRUE),

read.table(text = "nu_pregao    pcVar
3       2371 4.011461
47      2372 3.679907
91      2373 4.693034", header = TRUE))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM