【问题标题】:How to calculate with rows in a column in R如何用R中的列中的行进行计算
【发布时间】:2021-10-09 18:22:53
【问题描述】:

我正在尝试对列中的行进行计算: 我有一个产品的以下数据:

Day    Price
1      3$
2      12$
3      4$
4      2$
5      4$

我想将一天的价格变化除以前一天,例如第 2 天:

12$/3$ = 4 

结果应该是:

Day    Price    Calculation
1      3$       NA
2      12$      4
3      4$       0,33
4      2$       0,5
5      4$       2

我有一个包含 5000 个价格的清单。我还担心如何在第 1 天获得 NA,因为无法计算。

谢谢!

【问题讨论】:

    标签: r dataframe calculation


    【解决方案1】:

    这是dplyr 唯一使用gsub 而不是parse_number 的解决方案:

    library(dplyr)
    df %>% 
      mutate(Calculation=as.numeric(gsub("\\$", "", Price)),
             Calculation=round(Calculation/lag(Calculation), 2))
    
    Day Price Calculation
    1   1    3$          NA
    2   2   12$        4.00
    3   3    4$        0.33
    4   4    2$        0.50
    5   5    4$        2.00
    

    【讨论】:

      【解决方案2】:

      我们可以将当前值除以之前的值 (lag)。 $ 不在 numeric 类中考虑。我们可能需要提取 numeric 值 (parse_number) 并进行计算

      library(dplyr)
      df1 <- df1 %>%
          mutate(Calculation = readr::parse_number(as.character(Price)),
              Calculation = round(Calculation/lag(Calculation), 2))
      

      -输出

      df1
       Day Price Calculation
      1   1    3$          NA
      2   2   12$        4.00
      3   3    4$        0.33
      4   4    2$        0.50
      5   5    4$        2.00
      

      数据

      df1 <- structure(list(Day = 1:5, Price = c("3$", "12$", "4$", "2$", 
      "4$")), class = "data.frame", row.names = c(NA, -5L))
      

      【讨论】:

      • 感谢您的快速响应,尝试您的代码我收到错误:Error: Problem with mutate() column Calculationi Calculation = readr::parse_number(Price)x is.character(x) is not TRUE
      • @upflow 也许你有factor 类。尝试在我更新的代码中使用as.character
      • 谢谢,现在计算完毕。但不知何故,新列“计算”仍然缺失。
      • @upflow 只需将&lt;- 分配回原始数据,即df1 &lt;- df1 %&gt;% mutate(Calculation = readr::parse_number(as.character(Price)), Calculation = round(Calculation/lag(Calculation), 2))
      • 谢谢,现在我得到了需要的结果!一个简短的问题:是否有可能复制列Price,但将价格数据向下放置一行?那么对于Day 2:原始Price 将是12,而对于Price_duplicate 它将是3?
      【解决方案3】:

      基础 R 选项 -

      Price 列更改为数字并将当前Price 值减去前一个值。

      df$Price <- as.numeric(sub('$', '', df$Price, fixed = TRUE))
      df$Calculation <-  c(NA, df$Price[-1]/df$Price[-nrow(df)])
      df
      #  Day Price Calculation
      #1   1     3          NA
      #2   2    12       4.000
      #3   3     4       0.333
      #4   4     2       0.500
      #5   5     4       2.000
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多