gpt4 book ai didi

R data.table 按组替换所有缺失列的第一行

转载 作者:行者123 更新时间:2023-12-04 10:33:57 24 4
gpt4 key购买 nike

我有一个 data.table,我正在尝试做一些类似于 data[ !is.na(variable) ] 的事情.但是,对于完全缺失的组,我只想保留该组的第一行。所以,我正在尝试使用 by 进行子集化。我在网上做了一些研究并有一个解决方案,但我认为它效率低下。

我在下面提供了一个示例,显示了我希望实现的目标,我想知道这是否可以在不创建两个额外列的情况下完成。

d_sample = data.table( ID = c(1, 1, 2, 2, 3, 3), 
Time = c(10, 15, 100, 110, 200, 220),
Event = c(NA, NA, NA, 1, 1, NA))

d_sample[ !is.na(Event), isValidOutcomeRow := T, by = ID]
d_sample[ , isValidOutcomePatient := any(isValidOutcomeRow), by = ID]
d_sample[ is.na(isValidOutcomePatient), isValidOutcomeRow := c(T, rep(NA, .N - 1)), by = ID]
d_sample[ isValidOutcomeRow == T ]

编辑:以下是与 的一些速度比较thelatemail 弗兰克 具有 60K 行的更大数据集的解决方案。
d_sample = data.table( ID = sort(rep(seq(1,30000), 2)), 
Time = rep(c(10, 15, 100, 110, 200, 220), 10000),
Event = rep(c(NA, NA, NA, 1, 1, NA), 10000) )

thelatemail 的解决方案的运行时间为 20.65在我的电脑上。
system.time(d_sample[, if(all(is.na(Event))) .SD[1] else .SD[!is.na(Event)][1], by=ID])

Frank 的第一个解决方案的运行时间为 0
system.time( unique( d_sample[order(is.na(Event))], by="ID" ) )

Frank 的第二个解决方案的运行时间为 0.05
system.time( d_sample[order(is.na(Event)), .SD[1L], by=ID] )

最佳答案

这似乎有效:

unique( d_sample[order(is.na(Event))], by="ID" )

ID Time Event
1: 2 110 1
2: 3 200 1
3: 1 10 NA

或者, d_sample[order(is.na(Event)), .SD[1L], by=ID] .

扩展 OP 的示例,我还发现这两种方法的时间相似:
n = 12e4 # must be a multiple of 6
set.seed(1)
d_sample = data.table( ID = sort(rep(seq(1,n/2), 2)),
Time = rep(c(10, 15, 100, 110, 200, 220), n/6),
Event = rep(c(NA, NA, NA, 1, 1, NA), n/6) )

system.time(rf <- unique( d_sample[order(is.na(Event))], by="ID" ))
# 1.17
system.time(rf2 <- d_sample[order(is.na(Event)), .SD[1L], by=ID] )
# 1.24
system.time(rt <- d_sample[, if(all(is.na(Event))) .SD[1] else .SD[!is.na(Event)], by=ID])
# 10.42
system.time(rt2 <-
d_sample[ d_sample[, { w = which(is.na(Event)); .I[ if (length(w) == .N) 1L else -w ] }, by=ID]$V1 ]
)
# .13

# verify
identical(rf,rf2) # TRUE
identical(rf,rt) # FALSE
fsetequal(rf,rt) # TRUE
identical(rt,rt2) # TRUE

@thelatemail 解决方案的变化 rt2是最快的。

关于R data.table 按组替换所有缺失列的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40097041/

24 4 0