首页 文章

从其他数据帧的功能创建新的数据帧

提问于
浏览
0

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

我有两个数据帧 . 我们假装是为了解释:

df1

列表示收益类型:玉米,燕麦,小麦等 . 行表示一年中的月份,jan,feb等 . 元素表示在该特定月份内购买的该增益类型的每吨价格 .

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”,]  + .....

给我每个国家的费用,但仅限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

1 回答

  • 1

    你有两个选择:一个是使用 outer 函数,从df2的colnames提供'month'向量的输入和'country'向量,并使用一个从df1和df2中提取'cost'组件的函数 . (无法使用这种方法 . )你会得到一个'month' x 'country'矩阵 . 另一种方法是转换df2数据帧并使用all = TRUE进行合并,df1获取"long"格式数据帧,您可以使用公式对列进行列操作,然后重塑为'countries'中的"wide"格式 . 详细信息将取决于具体的数据设置,您还没有提供示例 .

    这将为您提供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)
    

相关问题