assign country-level value to several individual-level values

I have a problem with assigning values to my data. I have one data set which is country-level data, and one that is individual-level. I need to assign the country-level values to each individual observation. For example, I have 1000 individual answers from Argentina, and need to assign to every one of them a single value from the country-level data set. How would I do this?

You can use dpylr::left_join for this.

library(dplyr)

people <- data.frame(income = rnorm(10, 10000, 2000),
                     country = rep(LETTERS[1:2], each = 5))
nations <- data.frame(country = LETTERS[1:2], gdp = c(10000, 5000))

left_join(people, nations)
Joining, by = "country"
      income country   gdp
1  11167.139       A 10000
2   9226.737       A 10000
3  10022.757       A 10000
4  11940.153       A 10000
5  12313.464       A 10000
6   7827.194       B  5000
7   9383.204       B  5000
8   6045.494       B  5000
9   8678.369       B  5000
10 10103.826       B  5000

Or, if you'd prefer to do it in base R, use merge with all.* = TRUE , e.g.:

merge(people, nations, all.x = TRUE)
1 Like

Thank you so much, I had to do some extra steps but your explanation helped loads!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.