rbind data.frames 列表,同时在 R 中保留 NULL 元素

goc*_*lem 2 r list dataframe

我想使用 R将元素转换为rbindNA 。考虑以下示例,listdata.frameNULL

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
Run Code Online (Sandbox Code Playgroud)

Rol*_*and 5

从转换 NULL 元素开始:

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
Run Code Online (Sandbox Code Playgroud)