I have a dataset in a long data format:
Date Region X Y Z T D E F
01-01-2020 RegionA 2 4 2 3 2 3 4
01-01-2020 RegionB 1 3 2 2 3 3 3
01-01-2020 RegionC 1 4 4 2 3 4 2
01-01-2020 RegionD 2 4 2 3 2 4 4
01-01-2020 RegionE 1 3 2 2 2 2 2
02-01-2020 RegionA 2 4 7 3 2 3 4
02-01-2020 RegionB 1 3 2 2 2 3 3
02-01-2020 RegionC 1 4 4 8 3 4 2
02-01-2020 RegionD 2 3 2 3 2 4 4
02-01-2020 RegionE 1 3 2 2 2 2 2
Dates are many more but this should give you an idea about the format.
Then I have a second dataset, which contains further information about the population of these regions:
Region Pop
RegionA 2000
RegionB 4039
RegionC 24728
RegionD 3738
RegionE 2936
What I want to do is to divide one column in the first dataset by the population value for each region, across all dates. For example, if 'x' is GDP I want to divide the GDP by the population value at each different time point. For RegionA this would be 2/2000 and 2/2000 for each 01-01-2020 and 02-01-2020.
I am quite new to R and any help to get started solving this problem would be great.
Here there is a reproducible example
date<-as.Date(c("2020-02-24T18:00:00", "2020-02-24T18:00:00", "2020-02-
24T18:00:00", "2020-05-02T17:00:00", "2020-05-02T17:00:00",
"2020-05-02T17:00:00"))
regions<-c("RegionA", "RegionB", "RegionC","RegionA", "RegionB", "RegionC")
total<-c(1394, 1143, 18373, 168479, 65370, 26990)
df<-data.frame(date, regions, total)
and for the other dataframe:
regions<-c("RegionA", "RegionB", "RegionC")
pop<-c(1305283, 559084, 1935414)
mydf_pop<-data.frame(regions, pop)
Now: I tried various combination of
df >%>
left_join(mydf_pop)>%>
group_by(date, regions)>%>
mutate(total/pop)
which is clearly wrong.
Thank you.