R base
A solution only in R base can be with Reduce/merge
.
First, read the files. These two instructions assume that the only files that are in the current directory with the extension "csv"
are the three files that matter.
If the data has a comma as a decimal point, use read.csv
.
ficheiros <- list.files(pattern = "\\.csv")
list_df <- lapply(ficheiros, read.csv)
Now merge the files.
dados <- Reduce(function(x, y){merge(x, y, by = "paises", all = FALSE)}, list_df)
Like the merge
uses by default columns with common names and only combines lines with common values, the above code can be simplified.
Reduce(merge, list_df)
Bundle dplyr
After seeing the reply from Marcus Nunes, I noticed that Reduce
can also be applied to join problem (merge
or join
) various bases. But to only have the lines with common countries, inner_join
seems to be the right option.
library(dplyr)
Reduce(inner_join, list_df)
Test data
df1 <- data.frame(paises = letters[1:4], X = 1:4)
df2 <- data.frame(paises = letters[1:5], Y = 5:1)
df3 <- data.frame(paises = letters[c(1,2,4)], Z = rnorm(3))
list_df <- mget(ls(pattern = "^df"))