rbind data.frames的列表,同时在R中保留NULL元素 [英] rbind a list of data.frames while keeping NULL elements in R
本文介绍了rbind data.frames的列表,同时在R中保留NULL元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想rbind
一个data.frame
的一个list
,并使用R将NULL
个元素转换为NA.请考虑以下示例,
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
推荐答案
从转换NULL元素开始:
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
这篇关于rbind data.frames的列表,同时在R中保留NULL元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文