gpt4 book ai didi

r - 将数据帧的单列中的值向上移动,并在另一列中指定滞后

转载 作者:行者123 更新时间:2023-12-04 20:26:53 25 4
gpt4 key购买 nike

我想将不同国家/地区的价格调整到一个时区,这意味着将一列向上移动另一列中声明的滞后(移动是时差)。

使用这样的示例数据:

example=data.frame(country=c("IT","IT","GR","GR","GR","TR","TR","TR","TR"), 
price=c(200,150,300,480,590,638,237,438,555),
shift=c(0,0,1,1,1,2,2,2,2))

看起来像这样:
        country   price   shift
IT 200 0
IT 150 0
GR 300 1
GR 480 1
GR 590 1
TR 638 2
TR 237 2
TR 438 2
TR 555 2

我想得到以下结果:
        country   price   shift
IT 200 0
IT 150 0
GR 480 1
GR 590 1
GR NA 1
TR 438 2
TR 555 2
TR NA 2
TR NA 2

我尝试使用此线程中的解决方案:
R: Shift values in single column of dataframe UP
但由于它使用一个滞后值,因此并不完全适用。

最佳答案

使用 dplyr::lead

library(dplyr)

example %>%
group_by(shift) %>%
mutate(price = lead(price, unique(shift)))

或使用 data.table::shift
library(data.table)

setDT(example)[, price := shift(.(price), type = "lead", n = shift), .(shift)][]

给予
#>   country price shift
#> 1 IT 200 0
#> 2 IT 150 0
#> 3 GR 480 1
#> 4 GR 590 1
#> 5 GR NA 1
#> 6 TR 438 2
#> 7 TR 555 2
#> 8 TR NA 2
#> 9 TR NA 2

关于r - 将数据帧的单列中的值向上移动,并在另一列中指定滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58609995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com