与观察相关的列的正确滞后()

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

我有一个如下所示的数据框,我在其中通过对

lag()
列中的观察值使用
values
创建滞后列。我的数据框中的每一行都与特定的旅程相关联。我想把
lag()
操作改成现在这样,它不考虑
value
是否是新旅程的第一个,也就是说应该没有以前的记录。然后我想从我的数据框中删除该行。

通过运行 df_output,可以观察到想要的输出,但现在是手动完成的。

我的真实数据框包含大量的行,依次是旅程。

# Reproducible example
df <- data.frame(tours = c("kuu122", "kuu122", "ansc123123", "ansc123123", "ansc123123", "ansc123123", "baa3999", "baa3999", "baa3999", "baa3999"), order = c(4, 5, rep(c(1, 2, 3, 4), 2)), journey = c(1, 1, 2, 2, 2, 2, 3, 3, 3, 3), values = c(50, 60, 10, 20, 15, 13, 28, 15, 22, 14))

# Get the observed values at order_t
observed_values <- df$values
# Create lagged column
df$prev_values <- lag(observed_values, 1)

# TODO
# Remove row if prev_values are the first observation on a new journey
#???


df_output <- df[c(2, 4:6, 8:10),]
df_output
r dataframe row
3个回答
1
投票

row_number

按组获取除第一行以外的所有内容
library(dplyr) # >= 1.1.0

df %>% 
  filter(row_number() != 1, .by = tours)
       tours order journey values
1     kuu122     5       1     60
2 ansc123123     2       2     20
3 ansc123123     3       2     15
4 ansc123123     4       2     13
5    baa3999     2       3     15
6    baa3999     3       3     22
7    baa3999     4       3     14

1
投票

我们可以为此使用

slice

library(dplyr)

df_output <- df %>%
  group_by(journey) %>%
  slice(-1) %>%
  ungroup()

或者 dplyr >=1.1.0

df %>%
  slice(-1, .by=journey) 

1
投票

base R
一起使用
duplicated

subset(df, duplicated(journey))

-输出

         tours order journey values
2      kuu122     5       1     60
4  ansc123123     2       2     20
5  ansc123123     3       2     15
6  ansc123123     4       2     13
8     baa3999     2       3     15
9     baa3999     3       3     22
10    baa3999     4       3     14
© www.soinside.com 2019 - 2024. All rights reserved.