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

六月ゝ 毕业季﹏ 提交于 2021-01-19 04:50:55

问题


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!


回答1:


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



回答2:


Since you mention that you used subset and dcast to build each data frame, I suspect you have these data already all in one data frame in which case assigning the role of numerator and denominator might be all you need to do to in order to run the calculation using ddply. For instance, going with your example data and melting it back into a long-form data frame, would give you the following with a single ddply:

# data
DF1 <- data.frame(Name = c("Aaron", "Blake"), Jan = c(2, 5), Feb = c(4, 6), Mar = c(3, 4))
DF2 <- data.frame(Name = c("Aaron", "Blake"), Jan = c(4, 7), Feb = c(6, 6), Mar = c(6, 5))

# long format with 'numerator' and 'denominator' roles assigned
# (unnecessary if you already have long format, just assign numerator/denomninator)
library(reshape2)
df <- rbind(
  transform(
    melt(DF1, id.vars = "Name", variable.name = "Month"),
    role = "numerator"),
  transform(
    melt(DF2, id.vars = "Name", variable.name = "Month"),
    role = "denominator")
)

# ddply 
library(plyr)
ddply(df, .(Name, Month), summarize, 
      Result = value[role == "numerator"] / value[role == "denominator"])

#   Name Month     Result
# 1 Aaron   Jan 0.5000000
# 2 Aaron   Feb 0.6666667
# 3 Aaron   Mar 0.5000000
# 4 Blake   Jan 0.7142857
# 5 Blake   Feb 1.0000000
# 6 Blake   Mar 0.8000000


来源:https://stackoverflow.com/questions/33597577/dividing-two-data-frames-one-into-the-other-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!