我正在尝试使用列中的行进行计算:我有一个产品的以下数据:
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。
谢谢!
这里是使用gsub
而不是parse_number
:的仅dplyr
的解决方案
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
我们可以将当前值除以以前的值(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))
基本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