Thanks @andresrcs, I think I have to rephrase my question, since what I posted on my original question was a simplification of my problem and I'm afraid that the answer doesn't apply to it.
Here there is a second try:
library("dplyr")
I have the following data frame:
countries = data.frame(
country = c("USA", "United Kingdom", "China"),
president = c("Donald Trump", "Boris Johnson", "Xi Jinping")
)
countries
## country president
## 1 USA Donald Trump
## 2 United Kingdom Boris Johnson
## 3 China Xi Jinping
Also, I have the following mapping_car_country :
mapping_country_population_area = data.frame(
country = c("USA", "United Kingdom", "China"),
population = c("329963026", "66435600", "1399285880"),
area_sqm = c("3796742", "93788", "3722342")
)
mapping_country_population_area
## country population area_sqm
## 1 USA 329963026 3796742
## 2 United Kingdom 66435600 93788
## 3 China 1399285880 3722342
My goal is: mutate data frame: countries by adding a new column: popdensity accordingly with the mapping: mapping_country_population_area .
I tried the following which is not correct, but probably it is an starting point:
# hardcoding "USA" where it should be the country on data frame: `countries`
# I need to get a reference to the outer country somehow
countries = countries %>% mutate(
popdensity =
(mapping_country_population_area %>% dplyr::filter(country == "USA"))[["population"]] /
(mapping_country_population_area %>% dplyr::filter(country == "USA"))[["area_sqm"]]
)
## Warning in Ops.factor((mapping_country_population_area %>%
## dplyr::filter(country == : '/' not meaningful for factors
countries
## country president popdensity
## 1 USA Donald Trump NA
## 2 United Kingdom Boris Johnson NA
## 3 China Xi Jinping NA
Thanks!