Reputation: 954
I would like to rbind
a list
of data.frame
and transform NULL
elements into NA using R. Consider the following example,
l <- list(data.frame(C1 = 1, C2 = 2),
NULL,
data.frame(C1 = 3))
# bind_rows results
dplyr::bind_rows(l)
# C1 C2
# 1 1 2
# 2 3 NA
# Desired output
data.frame(C1 = c(1, NA, 3), C2 = c(2, NA, NA))
# C1 C2
# 1 1 2
# 2 NA NA
# 3 3 NA
Upvotes: 3
Views: 2787
Reputation: 132651
Start with transforming the NULL elements:
l <- lapply(l, function(x) if(is.null(x)) data.frame(C1 = NA) else x)
dplyr::bind_rows(l)
# C1 C2
#1 1 2
#2 NA NA
#3 3 NA
Upvotes: 6