Reputation: 119
I have two data frames as follows:
And I want to assign a specific value based on country and year. The result should be
Anyone know how to do automatically? Because table A has over 2,000 rows and 30 years.
Upvotes: 1
Views: 38
Reputation: 887028
An option is to reshape the second data into 'long' format and then do a join
library(dplyr)
library(tidyr)
df2 %>%
pivot_longer(cols = -Country, names_to = 'Year', values_to = 'Value') %>%
left_join(df1, .)
# Country Year Value
#1 Country1 1990 value1
#2 Country2 1991 value5
#3 Country3 1991 value6
df1 <- structure(list(Country = c("Country1", "Country2", "Country3"
), Year = c("1990", "1991", "1991")), row.names = c(NA, -3L),
class = "data.frame")
df2 <- structure(list(Country = c("Country1", "Country2", "Country3"
), `1990` = c("value1", "value2", "value3"), `1991` = c("value4",
"value5", "value6")), class = "data.frame", row.names = c(NA,
-3L))
Upvotes: 1