如何用R中的列中的行进行计算

How to calculate with rows in a column in R

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

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 个价格的清单。我也担心如果无法计算,如何在第一天获得 NA。

谢谢!

我们可以将当前值除以之前的值 (lag)。在numeric class中不考虑$。我们可能需要提取 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))

这是 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

基础 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