我是 R 的新手,所以我可能很难提出我的问题。请多多包涵。
我有两个数据框。为了解释起见,我们假设:
df1
柱形代表收益类型:玉米、燕麦、小麦等。
行代表一年中的月份,一月、二月等。
Elements 代表在该特定月份购买的增益类型的每吨价格。
df2
代表国家的列:西班牙、智利、墨西哥等。
该框的行代表与该国家/地区打交道的额外费用,可能是:
每个国家的包装成本、运输成本、国家进口税、检验费等。
现在我想构建第三个数据框:
df3
它代表所有国家每月谷物组合(例如 10% 玉米、50% 燕麦等)的总成本以及运输、税收等相关成本 假设有一个等式(使用 df1 和 df2 的数据)计算每个国家每月给定谷物组合的总成本以及每个国家的额外成本。
为了简洁起见,我们假设三月份总成本的等式的一部分,西班牙是
cost <- .10 * df1[ “mar”,”oats”] + df2[“tax”,”Spain”] + .....
对我来说,选择第二个数据帧的元素并与第一个数据帧的列进行算术运算以获得结果是很简单的。对于特定国家:
cost <- .10 * df1[ ,”oats”] + df2[“tax”,”Spain”] + .....
这给了我西班牙每个月的费用
问题是:我必须对每个国家重复相同的算术。
另一个版本:
cost <- .10 * df1[ ,”oats”] + df2[“tax”,] + .....
为我提供每个国家/地区的费用,但仅限一月份
我想要一组方程,可以计算出所有县每月的总成本。另外一句话,df3
将具有相同的行数df1
(月),以及相同的列数df2
(国家)。
编辑...粘贴在已关闭问题中发布的示例中:
# build df1 - cost of grains (with goofy data so I can track the arithemetic)
v1 <- c(1:12)
v2 <- c(13:24)
v3 <- c(25:36)
v4 <- c(37:48)
grain <- data.frame("wheat"=v1,"oats"=v2,"corn"=v3,"rye"=v4)
grain
# build df2 - additional costs (again, with goofy data to see what is being used where and when)
w1 <- c(1.3:4.3)
w2 <- c(5.3:8.3)
w3 <- c(9.3:12.3)
w4 <- c(13.3:16.3)
cost <- data.frame("Spain"=w1,"Peru"=w2,"Mexico"=w3,"Kenya"=w4)
row.names(cost) <- c("packing","shipping","tax","inspection")
cost
# assume 10% wheat, 30% oats and 60% rye with some clown-equation for total cost
# now for my feeble attempt at getting a dataframe that has 12 rows (months) and 4 column (countries)
total_cost <- data.frame( 0.1*grain[,"wheat"] +
0.3*grain[,"oats"] +
0.6*grain[,"rye"] +
cost["packing","Mexico"] +
cost["shipping","Mexico"] +
cost["tax","Mexico"] +
cost["inspection","Mexico"] )
total_cost