将缺失的时间行插入到数据框中
Insert missing time rows into a dataframe
假设我有一个数据框:
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 在评论中提到的那样,如果特定的 'time' 值不存在于所有组中,上述方法将失败。可能这会更笼统。
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)
。
假设我有一个数据框:
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 在评论中提到的那样,如果特定的 'time' 值不存在于所有组中,上述方法将失败。可能这会更笼统。
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)
。