Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing Two Data Frames (One into the Other) in R

How would I divide one data frame by another? The two data frames have the same columns and same rows, but I need to divide every intersect with its corresponding intersect into a new data frame, e.g. below:

DF1
Name    Jan    Feb    Mar
Aaron     2      4      3
Blake     5      6      4

DF2
Name    Jan    Feb    Mar
Aaron     4      6      6
Blake     7      6      5

DF1/DF2 = DF3

DF3 (result)
Name    Jan    Feb    Mar
Aaron   0.5    0.7    0.5
Blake   0.7    1.0    0.8

I'm using subset then dcast to build each data frame, but having a hard time figuring out how to divide them. Thanks for your help!

like image 873
stevenjoe Avatar asked Dec 19 '22 22:12

stevenjoe


1 Answers

We divide the numeric columns in both 'DF1' and 'DF2' (by removing the first column) and cbind with the first column.

DF3 <- cbind(DF1[1],round(DF1[-1]/DF2[-1],1))
DF3
#    Name Jan Feb Mar
# 1 Aaron 0.5 0.7 0.5
# 2 Blake 0.7 1.0 0.8
like image 179
akrun Avatar answered Dec 21 '22 13:12

akrun