С base R
мы можем сделать
out <- merge(expand.grid(lapply(mydata[c('class', 'days')],
unique)), mydata, all.x = TRUE)
out$value[is.na(out$value)] <- 0
out
# class days value
#1 0 1 100
#2 0 2 30
#3 0 3 50
#4 3 1 0
#5 3 2 70
#6 3 3 50
ПРИМЕЧАНИЕ: пакеты не используются
Или с data.table
library(data.table)
setDT(mydata)[CJ(class, days, unique = TRUE),
on = .(class, days)][is.na(value), value := 0][]
# class value days
#1: 0 100 1
#2: 0 30 2
#3: 0 50 3
#4: 3 0 1
#5: 3 70 2
#6: 3 50 3
Или используя crossing/left_join
из tidyverse
library(dplyr)
library(tidyr)
tidyr::crossing(class = unique(mydata$class),
days = unique(mydata$days)) %>%
left_join(mydata) %>%
mutate(value = replace_na(value, 0))
# A tibble: 6 x 3
# class days value
# <dbl> <dbl> <dbl>
#1 0 1 100
#2 0 2 30
#3 0 3 50
#4 3 1 0
#5 3 2 70
#6 3 3 50
data
mydata <- structure(list(class = c(3, 0, 3, 0, 0), value = c(50, 50, 70,
30, 100), days = c(3, 3, 2, 2, 1)), class = "data.frame", row.names = c(NA,
-5L))