在R中有滞后的单列中的移位值

问题描述 投票:0回答:1

我有以下DF:

example=data.frame(Code=c(A1,A1,A1,A2,A2,A2,A2,A3,A3,A3,A3,A3), Week=c(1,2,3,1,2,3,4,1,2,3,4,5), Price=c(10,10,8,4,4,6,6,15,20,20,20,20))

DF看起来像这样:

        Code   Week   Price
    1    A1     1      10
    2    A1     2      10
    3    A1     3       8
    4    A2     1       4
    5    A2     2       4
    6    A2     3       6
    7    A2     4       6
    8    A3     1      15
    9    A3     2      20
   10    A3     3      20
   11    A3     4      20
   12    A3     5      20

我想在不更改DF其余部分的情况下将价格值向上移动两行,但是不能将价格移动到其他代码,例如:

      Code   Week   Price
  1    A1     1       8
  2    A1     2      NA
  3    A1     3      NA
  4    A2     1       6
  5    A2     2       6
  6    A2     3      NA
  7    A2     4      NA
  8    A3     1      20
  9    A3     2      20
 10    A3     3      20
 11    A3     4      NA
 12    A3     5      NA

我已经看到了将列值上移的方法,但我真的不想将价格上移到另一个代码。

[请给我一些帮助。谢谢。

r dataframe shift
1个回答
1
投票

我们可以在lead中使用dplyr

library(dplyr)
df %>%  group_by(Code) %>%  mutate(Price = lead(Price, 2))

#  Code   Week Price
#  <fct> <int> <int>
# 1 A1      1     8
# 2 A1      2    NA
# 3 A1      3    NA
# 4 A2      1     6
# 5 A2      2     6
# 6 A2      3    NA
# 7 A2      4    NA
# 8 A3      1    20
# 9 A3      2    20
#10 A3      3    20
#11 A3      4    NA
#12 A3      5    NA

shift中的data.table

library(data.table)
setDT(df)[, Price := shift(Price, 2, type = "lead"), Code]

基本中没有可用的就绪函数来执行此操作,但我们可以使用tail并附加NA值。

df$Price <- with(df,ave(Price, Code, FUN = function(x) c(tail(x, -2), rep(NA, 2))))
© www.soinside.com 2019 - 2024. All rights reserved.