代码之家  ›  专栏  ›  技术社区  ›  user113156

使用行字符串中的公司帐户在dplyr price*qty中进行变异

  •  0
  • user113156  · 技术社区  · 7 年前

    我有以下公司数据,我试图计算价格*数量从一行。我的问题是我似乎不能 行中的值使用 dplyr .

    x %>%
      group_by(firm) %>%
      select(Var) %>%
      mutate(revenues = price*qty)
    

    mutate() 函数正在查找 price qty .

    df <- structure(list(firm = c("firm1", "firm1", "firm1", "firm2", "firm2", 
    "firm2"), Var = c("price", "qty", "package", "price", "qty", 
    "package"), `2018-03` = c("199309", "10901", "210210", "25370", 
    "4535", ""), `2017-03` = c("143736", "7065", "150801", "21374", 
    "", "652"), `2016-03` = c("106818", "8878", "115696", "11738", 
    "", "451"), `2015-03` = c("108193", "17806", "125999", "11163", 
    "", "256"), `2014-03` = c("33045", "12029", "45074", "16006", 
    "", "191"), `2013-03` = c("30396", "2919", "33315", "4952", "", 
    "208"), `2012-03` = c("16857", "5480", "22337", "1315", "", "97"
    ), `2011-12` = c("3433", "8219", "11652", "559", "", ""), `2010-12` = c("3254", 
    "6803", "10057", "94", "", ""), `2009-12` = c("2749", "4518", 
    "7266", "38", "", "")), .Names = c("firm", "Var", "2018-03", 
    "2017-03", "2016-03", "2015-03", "2014-03", "2013-03", "2012-03", 
    "2011-12", "2010-12", "2009-12"), row.names = 5:10, class = "data.frame")
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   G. Grothendieck    7 年前

    有两个问题:

    • 应该是数字的列实际上是字符
    • 没有 price qty

    要解决此问题,请转换名称以开头的列 2 然后使用 gather spread 价格 列来执行计算。

    library(dplyr)
    library(tidyr)
    
    df %>% 
      mutate_at(vars(starts_with("2")), as.numeric) %>% 
      gather(date, value, -firm, -Var) %>% 
      spread(Var, value) %>% 
      mutate(revenue = price * qty)
    

    给:

        firm    date package  price   qty    revenue
    1  firm1 2009-12    7266   2749  4518   12419982
    2  firm1 2010-12   10057   3254  6803   22136962
    3  firm1 2011-12   11652   3433  8219   28215827
    4  firm1 2012-03   22337  16857  5480   92376360
    5  firm1 2013-03   33315  30396  2919   88725924
    6  firm1 2014-03   45074  33045 12029  397498305
    7  firm1 2015-03  125999 108193 17806 1926484558
    8  firm1 2016-03  115696 106818  8878  948330204
    9  firm1 2017-03  150801 143736  7065 1015494840
    10 firm1 2018-03  210210 199309 10901 2172667409
    11 firm2 2009-12      NA     38    NA         NA
    12 firm2 2010-12      NA     94    NA         NA
    13 firm2 2011-12      NA    559    NA         NA
    14 firm2 2012-03      97   1315    NA         NA
    15 firm2 2013-03     208   4952    NA         NA
    16 firm2 2014-03     191  16006    NA         NA
    17 firm2 2015-03     256  11163    NA         NA
    18 firm2 2016-03     451  11738    NA         NA
    19 firm2 2017-03     652  21374    NA         NA
    20 firm2 2018-03      NA  25370  4535  115052950
    
    推荐文章