R语言 删除满足条件的每个ID的最后一项

kb5ga3dv  于 2022-12-30  发布在  其他
关注(0)|答案(2)|浏览(272)

我有一个多个人行为事件的数据集。它看起来像:

ID  Behavior  Order
A   Bucket    1
A   Tube      2
A   Bucket    3
A   Tube      4
A   Push      5
B   Bucket    1
B   Tube      2
B   Bucket    3
B   Tube      4
C   Bucket    1
C   Tube      2
C   Push      3
C   Bucket    4
C   Tube      5

我正在尝试删除个人的最后一个条目,其中最后一个条目是“推送”行为。
我首先使用以下代码找到了哪些人的最后行为是“推”:

LastBehaviour <- aggregate(Events[,"Behavior"], list(Events$Observation.id), tail, 1)
FixPush<-LastBehaviour[which(LastBehaviour$Behavior=="Push" ),"Group.1"]

我遇到的问题是如何根据“FixPush”中的列表删除最后一行的个人。

df <- df %>%
  group_by(Observation.id%in%FixPush)%>%
  arrange(Order)%>%
  head(-1) %>%
  glimpse()

现在这段代码只删除了一行。我假设是整个数据集的最后一行。我如何删除行为为“推”的每个个体的最后一个条目?

wnrlj8wa

wnrlj8wa1#

在dplyr中,使用分组过滤器删除Behavior等于"Push"且等于row_number() == n()的行(这意味着它是组中的最后一行)。

library(dplyr)

Events %>% 
  group_by(ID) %>% 
  filter(!(Behavior == "Push" & row_number() == n())) %>% 
  ungroup()
# A tibble: 13 × 3
   ID    Behavior Order
   <chr> <chr>    <dbl>
 1 A     Bucket       1
 2 A     Tube         2
 3 A     Bucket       3
 4 A     Tube         4
 5 B     Bucket       1
 6 B     Tube         2
 7 B     Bucket       3
 8 B     Tube         4
 9 C     Bucket       1
10 C     Tube         2
11 C     Push         3
12 C     Bucket       4
13 C     Tube         5
3ks5zfa0

3ks5zfa02#

使用data.table的另一个选项
其中.SD是每组ID的数据子集。然后删除Behavior =="Push" AND Order ==. N的任何行。其中. N表示每组的总行数。

library(data.table)

# sample data
df = data.table(
  ID = c(rep("A",5),rep("B",4), rep("C",5)),
  Behavior = c("Bucket","Tube","Bucket","Tube","Push","Bucket","Tube","Bucket","Tube","Bucket","Tube","Push","Bucket","Tube")
)
df[, Order := 1:.N, by = ID]

# subsetting
df = df[, .SD[!(Behavior == "Push" & Order == .N)], by = ID]
> df
    ID Behavior Order
 1:  A   Bucket     1
 2:  A     Tube     2
 3:  A   Bucket     3
 4:  A     Tube     4
 5:  B   Bucket     1
 6:  B     Tube     2
 7:  B   Bucket     3
 8:  B     Tube     4
 9:  C   Bucket     1
10:  C     Tube     2
11:  C     Push     3
12:  C   Bucket     4
13:  C     Tube     5

相关问题