我的表(称为MGIT(中有四个ID列:Ext_ID_1到_4。有时同一个数字出现在它们的不同行中,我需要过滤这些行以进行进一步分析,例如:
启动状态:
Ext_ID Ext_ID_4
1111 2222
3333 4444
5555 1111
6666 7777
8888 9999
9999 1010
期望的过滤结果:
Ext_ID Ext_ID_4
1111 2222
5555 1111
8888 9999
9999 1010
为了更清晰的管理,我只想一次将两者进行比较。
通过之前在StackOverflow中的问题,我发现了以下代码:
Dupl = MGIT[,c('Ext_ID','Ext_ID_4')]
Result <- MGIT[duplicated(Dupl) | duplicated(Dupl, fromLast=TRUE),]
但它只在列内返回重复的值(实际上,只在Ext_ID内,但我相信ID_4本身没有重复的值(。
我是一个编程初学者,对语言一无所知。
我想您希望这能适用于所有四列,而不仅仅是示例中的两列。
这里有一个解决方案,无论有多少";Ext_ID";您拥有的列:
library(dplyr)
# Recreate the data from your example
df <- tibble::tribble(
~Ext_ID, ~Ext_ID_4,
1111, 2222,
3333, 4444,
5555, 1111,
6666, 7777,
8888, 9999,
9999, 1010
)
# The actual code you need - just replace `df` with the name of your table
df %>%
filter(
if_any(
starts_with("Ext_ID"),
~ .x %>% purrr::map_lgl(~sum(df == .x) > 1)
)
)
# The output:
#> # A tibble: 4 x 2
#> Ext_ID Ext_ID_4
#> <dbl> <dbl>
#> 1 1111 2222
#> 2 5555 1111
#> 3 8888 9999
#> 4 9999 1010
解释:
~ .x %>% purrr::map_lgl(~sum(df == .x) > 1)
检查列中的每个值是否在数据帧中显示不止一次- CCD_ 2确保对以"0"开头的所有列都这样做;Ext_ID">
- CCD_ 3使CCD_ 4为任意列保留df中至少有1个重复值的行
基本R解决方案:
#Select whatever column you want
cols <- unlist(dat[, c('Ext_ID','Ext_ID_4')])
#Get the values that appear at least twice
uni <- unique(cols[ave(cols, cols, FUN=length) > 1])
#Filter if any of the row values match with uni
dat[apply(apply(dat, 1, function(x) x %in% uni), 2, any), ]
Ext_ID Ext_ID_4
1 1111 2222
3 5555 1111
5 8888 9999
6 9999 1010