gpt4 book ai didi

r - 反连接但只返回 "previous"缺失行

转载 作者:行者123 更新时间:2023-12-03 07:31:52 25 4
gpt4 key购买 nike

示例数据:

library(dplyr)
x <- data.frame(name = c(rep('Alice', 4), rep('Bob', 3)),
timestamp = c(1, 5, 10, 11, 1, 3, 4), stringsAsFactors = F)

y <-
base::merge(I(c('Alice', 'Bob')), c(1:3, 5:15)) # note missing time stamp = 4
names(y) <- names(x)
y <-
y %>%
arrange(name,timestamp)

我想找到数据帧 anti_join(y,x) 中每个连续 block (使用 timestamp 排序)的最后一行(如果存在)。

使用示例数据构建anti_join:

x_missing <-
dplyr::anti_join(y, x) %>%
arrange(name,timestamp)

这给出了

> head(x_missing, 11)
name timestamp
1 Alice 2
2 Alice 3
3 Alice 6
4 Alice 7
5 Alice 8
6 Alice 9
7 Alice 12
8 Alice 13
9 Alice 14
10 Alice 15
11 Bob 2

我希望解决方案是:

  name timestamp
Alice 3
Alice 9
Alice 15
...

该解决方案需要比计算 anti_join(y,x) 更快,当 x,y 很大时,计算速度会非常慢。

最佳答案

这提高了反连接的速度,并使用循环来获取您想要的行,但是肯定有一些比使用我的 hack-ish 循环更好的方法来选择行。

library(dplyr)
x <- data.frame(name = c(rep('Alice', 4), rep('Bob', 3)),
timestamp = c(1, 5, 10, 11, 1, 3, 4), stringsAsFactors = F)

y <-
base::merge(I(c('Alice', 'Bob')), c(1:3, 5:15)) # note missing time stamp = 4
names(y) <- names(x)


y <-
y %>%
arrange(name,timestamp)

x$nt <- paste(x$name,x$timestamp)
y$nt <- paste(y$name,y$timestamp)

ynt <- y[!y$nt %in% x$nt,] # should be faster

tmp <- data.frame(name=NA,timestamp=NA)
for(i in 2:nrow(ynt)){
if((ynt[i-1,2]+1) < (ynt[i,2])){tmp <- rbind(ynt[i-1,1:2],tmp)}
if(!((ynt[i-1,1]) == (ynt[i,1]))){tmp <- rbind(ynt[i-1,1:2],tmp)}
if(i == nrow(ynt)){tmp <- rbind(ynt[i,1:2],tmp)}
}

tmp <- tmp[order(tmp$name,tmp$timestamp),]; tmp <- tmp[!is.na(tmp$name),]
tmp

name timestamp
Alice 3
Alice 9
Alice 15
...

关于r - 反连接但只返回 "previous"缺失行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37980555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com