在不太复杂但对我来说新鲜的东西上需要帮助。我有一个数据帧df,其中包含一列Product.id和一个价格Price。
Product.id price
A 11.5
A 11.5
A 12
A 13
A 13
B 9.25
B 9.75
B 9.75
B 9.5
我想使用自定义功能检查价格是否比上个月有所变化:
Check.Price.Change <- function(Vector){
for(x in 1:nrow(Vector)){
if(Vector[x] != Vector[x-1]){
TRUE
}
}
}
df <- df %>%
group_by(Product.id) %>%
mutate(if.Price.change = lapply(Price, Check.Price.Change))
我得到错误:
Error in 1:nrow(Vector) : argument of length 0
Called from: FUN(X[[i]], ...)
请问正确的方法是什么?
我们可以使用lag
indplyr
与上一个条目进行比较。
library(dplyr)
df %>% group_by(Product.id) %>% mutate(is_changed = price != lag(price))
# Product.id price is_changed
# <fct> <dbl> <lgl>
#1 A 11.5 NA
#2 A 11.5 FALSE
#3 A 12 TRUE
#4 A 13 TRUE
#5 A 13 FALSE
#6 B 9.25 NA
#7 B 9.75 TRUE
#8 B 9.75 FALSE
#9 B 9.5 TRUE
同样,有一个shift
函数data.table
的默认type
值为"lag"
library(data.table)
setDT(df)[, is_changed := price != shift(price), by = Product.id]
数据
df <- structure(list(Product.id = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L), .Label = c("A", "B"), class = "factor"), price = c(11.5,
11.5, 12, 13, 13, 9.25, 9.75, 9.75, 9.5)), class = "data.frame",
row.names = c(NA, -9L))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句