Form a dataframe from 3

Asked

Viewed 41 times

2

I have 3 CSV files with 3 data frames, and one brings the columns países and população, another bring países and área and another brings países and expectativa de vida. In the first, there are 195 records, in the second, 194 and in the third, 187.

I need to be able to form a data frame with países, população, área and expectativa de vida, but, for this, I want to take only the countries that appear in the 3 data frames and that the other columns be filled with the respective records for each country.

2 answers

3

The function left_join package dplyr does exactly what is requested. However, it only works with two data frames at a time, so it needs to be applied in two opportunities.

Assuming that data frames are called df1, df2 and df3, do

library(dplyr)
df_final <- left_join(left_join(df1, df2), 
                      df3)

2

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"))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.