r - 如何只删除连续的重复行?
问题描述
仅当它们连续出现时,我才需要删除数据框中的所有重复项。我尝试了 distinct() 函数,但它删除了所有重复项 - 所以我需要一个不同的代码,让我有机会自定义并说仅当重复项是连续的并且仅针对特定列时才删除。
这是我的数据示例:
Subject Trial Event_type Code Time
23 VP02_RP 15 Picture face01_n 887969
24 VP02_RP 15 Sound mpossound_test5 888260
25 VP02_RP 15 Picture pospic_test5 906623
26 VP02_RP 15 Nothing ev_mnegpos_adj_onset 928623
27 VP02_RP 15 Response 15 958962
28 VP02_RP 18 Picture face01_p 987666
29 VP02_RP 18 Sound mpossound_test6 987668
30 VP02_RP 18 Picture negpic_test6 1006031
31 VP02_RP 18 Nothing ev_mposnegpos_adj_onset 1028031
32 VP02_RP 18 Response 15 1076642
33 VP02_RP 19 Response 13 1680887
正如您在第 32 行和第 33 行中看到的那样,我有两个连续的响应,我只想保留第一个。所以我想删除我的 Event_type 列上所有重复的连续行。
我该怎么办?
解决方案
一个潜在的 tidyverse 解决方案:
library(tidyverse)
df1 <- data.frame(
stringsAsFactors = FALSE,
row.names = c("23","24","25","26","27",
"28","29","30","31","32","33"),
Subject = c("VP02_RP","VP02_RP","VP02_RP",
"VP02_RP","VP02_RP","VP02_RP","VP02_RP","VP02_RP",
"VP02_RP","VP02_RP","VP02_RP"),
Trial = c(15L, 15L, 15L, 15L, 15L, 18L, 18L, 18L, 18L, 18L, 19L),
Event_type = c("Picture","Sound","Picture",
"Nothing","Response","Picture","Sound","Picture",
"Nothing","Response","Response"),
Code = c("face01_n","mpossound_test5",
"pospic_test5","ev_mnegpos_adj_onset","15","face01_p",
"mpossound_test6","negpic_test6",
"ev_mposnegpos_adj_onset","15","13"),
Time = c(887969L,888260L,906623L,
928623L,958962L,987666L,987668L,1006031L,1028031L,
1076642L,1680887L)
)
df1 %>%
filter(Event_type != lag(Event_type, 1))
#> Subject Trial Event_type Code Time
#> 24 VP02_RP 15 Sound mpossound_test5 888260
#> 25 VP02_RP 15 Picture pospic_test5 906623
#> 26 VP02_RP 15 Nothing ev_mnegpos_adj_onset 928623
#> 27 VP02_RP 15 Response 15 958962
#> 28 VP02_RP 18 Picture face01_p 987666
#> 29 VP02_RP 18 Sound mpossound_test6 987668
#> 30 VP02_RP 18 Picture negpic_test6 1006031
#> 31 VP02_RP 18 Nothing ev_mposnegpos_adj_onset 1028031
#> 32 VP02_RP 18 Response 15 1076642
推荐阅读
- java - 本地主机以外的 Tomcat9 Web 访问失败
- html - 使项目仅在 xs 屏幕的下拉按钮中可见
- python - TypeError:预期的字符串或类似字节的object.in django
- c# - 循环中的异步睡眠
- python - 为什么我得到具有相同纬度和经度的不同 h3 索引
- android - Unity - Android 10 - BLE 蓝牙 - 背景位置
- spring-security - 如何为动态用户数配置 Spring Security
- python - 你知道为什么过滤后的输出总是从零开始吗?辛辣过滤蟒蛇脑电图
- amazon-web-services - 如何使用 vpc 安全组来限制对我的 Lambda 的入站访问?
- python - 如何在 Python 中用烧瓶形式替换标准输入()