Say that I have running id from 1 to n, and a value column:
set.seed(1)
x <- data.frame(c(1:10),rnorm(10,10, sd = 2.5))
colnames(x) <- c("id", "value")
id value
1 1 8.433865
2 2 10.459108
3 3 7.910928
4 4 13.988202
5 5 10.823769
6 6 7.948829
7 7 11.218573
8 8 11.845812
9 9 11.439453
10 10 9.236529
Now let's imagine that I have for some reason lost some of that data, but I nevertheless need to fill it with some value
# Let's lose data
(x <- x[-5,])
Now I am missing observation #5, but I still need to replace it with a value (e.g. 0 or NA). Note that in reality I don't necessary know what observation ID is missing.
This is what I wrote, and it works. However, I am wondering whether there is a vectorized way of doing this (or a more efficient way in general)?
f <- function(x, fill_value){
# Get number of rows
n <- nrow(x)
max_id <- max(x$id)
# Get missing data position
no_data_position <- which(!(1:max_id %in% x$id))
# Fill missing data
out <- data.frame()
start <- 0
counter <- 1
for(i in 1:max_id){
if(!i %in% no_data_position){
out[start + i, "id"] <- start + i
out[start + i, "value"] <- x$value[counter]
counter <- counter + 1
} else {
out[start + i, "id"] <- start + i
out[start + i, "value"] <- fill_value
}
}
return(out)
}
f(x, NA)
id value
1 1 8.433865
2 2 10.459108
3 3 7.910928
4 4 13.988202
5 5 NA
6 6 7.948829
7 7 11.218573
8 8 11.845812
9 9 11.439453
10 10 9.236529