简体   繁体   中英

How to divide a column for one dataframe by the column from another dataframe

I have a data frame with numbers of doctors in some cities in Brazil (data frame A). I have another data frame (data frame B) with the cities population (all of them). How can I obtain the value of number of doctors divided by the city population. Note that I have more cities in B than in A.

> A
 City Doctors 
 A          3
 C          4
 E          5
> B
 City     Pop 
 A          100
 B          20
 C          30
 D          40
 E          500
 F          10

I expect the following:

> Doc_divided_by_Pop
 City  Doctors_Pop
 A               3/100
 C               4/30
 E               5/500

Here's a way using match from base R -

A$Doctors_Pop <- A$Doctors / B$Pop[match(A$City, B$City)]

Another way using merge -

result <- merge(A, B, by = "City", all.x = TRUE)

result$Doctors_Pop <- result$Doctors / result$Pop

You could also do this with an "update join" using data.table

library(data.table)
setDT(A)
setDT(B)

A[B, on = .(City), Doctors_Pop := Doctors/Pop]

A
#    City Doctors Doctors_Pop
# 1:    A       3   0.0300000
# 2:    C       4   0.1333333
# 3:    E       5   0.0100000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM