【问题标题】:create new data frame from a function of other data frames从其他数据框的功能创建新的数据框
【发布时间】:2012-09-10 15:13:35
【问题描述】:

我是 R 的新手,我可能很难问我的问题。请多多包涵。

我有两个数据框。为了解释,我们假装:

df1

列代表收益类型:玉米、燕麦、小麦等。 Rows 代表一年中的月份,一月,二月等。 Elements 表示在该特定月份购买的那种收益类型的每吨价格。

df2

代表国家的列:西班牙、智利、墨西哥等。 此框架的行代表与该国家打交道的额外成本,可能是: 每个国家的包装成本、运输成本、国家进口税、检验费等。

现在我要构建第三个数据框:

df3

它表示所有国家/地区每月谷物组合的总成本(例如 10% 玉米、50% 燕麦……)以及相关的运输、税收等成本 假设有是一个方程(使用来自 df1 和 df2 的数据)计算给定谷物组合每个国家/地区每月的总成本以及每个国家/地区的额外成本。

为简洁起见,让我们假设 3 月份总成本等式的一部分,而西班牙是

cost <- .10 * df1[ “mar”,”oats”]  + df2[“tax”,”Spain”]  + .....

选择第二个数据帧的元素并对第一个数据帧的列进行算术运算以获得结果对我来说很简单。对于特定国家/地区:

cost <- .10 * df1[ ,”oats”]  + df2[“tax”,”Spain”]  + .....

这给了我西班牙每个月的费用

问题是:我必须对每个国家重复相同的算术。

另一个版本:

  cost <- .10 * df1[ ,”oats”]  + df2[“tax”,]  + .....

提供每个国家/地区的费用,但仅限 1 月份

我想要一组方程式,它可以为我提供所有县每月的总成本。换句话说,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

【问题讨论】:

标签: r


【解决方案1】:

您有几个选择:一个是使用outer 函数,从 df2 的 colnames 提供“月”向量和“国家”向量的输入,并使用一个可以提取“成本”的函数来自 df1 和 df2 的组件。 (无法使这种方法发挥作用。)您将得到一个“月”x“国家”矩阵。另一种方法是转置 df2 数据框并使用 all=TRUE 与 df1 合并,获取“长”格式数据框,您可以从中使用公式进行列操作,然后重塑为“国家”中“宽”的格式。详细信息取决于具体的数据设置,您尚未提供示例。

这将为您提供 12 x 4 的月份和国家/地区组合网格:

 dfrm <- expand.grid(grain$months,  colnames(cost) )

这将为您提供一个函数,该函数采用月份值和国家/地区值并计算上述表达式:

 costcros <- function(x) { sum(grain[ grain[, 'months'] == x[1], c(1,2,4)]*c(0.1,0.3,0.6) ) + 
                           sum( cost[, x[2]]) }

这会将计算添加到 dfrm 的每一行:

 dfrm$crosscost <- apply(expand.grid(grain$months,  colnames(cost) ), 1,  costcros)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多