假设我有一个数据框:
df <- data.frame(group = c('A','A','A','B','B','B'),
time = c(1,2,4,1,2,3),
data = c(5,6,7,8,9,10))
我想要做的是将数据插入序列中丢失的数据框。因此,在上面的示例中,对于组A,我丢失了
time
= 3的数据,对于组B,缺少了time
= 4的数据。我实际上想将0替换为data
列。我将如何添加这些额外的行?
目标是:
df <- data.frame(group = c('A','A','A','A','B','B','B','B'),
time = c(1,2,3,4,1,2,3,4),
data = c(5,6,0,7,8,9,10,0))
我的真实数据是数千个数据点,因此无法手动进行。
最佳答案
您可以尝试merge/expand.grid
res <- merge(
expand.grid(group=unique(df$group), time=unique(df$time)),
df, all=TRUE)
res$data[is.na(res$data)] <- 0
res
# group time data
#1 A 1 5
#2 A 2 6
#3 A 3 0
#4 A 4 7
#5 B 1 8
#6 B 2 9
#7 B 3 10
#8 B 4 0
或使用
data.table
library(data.table)
setkey(setDT(df), group, time)[CJ(group=unique(group), time=unique(time))
][is.na(data), data:=0L]
# group time data
#1: A 1 5
#2: A 2 6
#3: A 3 0
#4: A 4 7
#5: B 1 8
#6: B 2 9
#7: B 3 10
#8: B 4 0
更新
如评论中提到的@thelatemail,如果所有组中都不存在特定的“时间”值,则上述方法将失败。也许这会更笼统。
res <- merge(
expand.grid(group=unique(df$group),
time=min(df$time):max(df$time)),
df, all=TRUE)
res$data[is.na(res$data)] <- 0
并类似地在data.table解决方案中将
time=unique(time)
替换为time= min(time):max(time)
。关于r - 将缺少的时间行插入数据框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31150028/