就像akrun说的那样,您应该有一个else分支,它返回x以防它不是空的,现在你的代码总是产生空的。否则,我还会准备一个合适的空data.frame,如果您的数据中总是有特定的列。这是通过准备具有符号的列的代码,数字(0),字符(0),整数(0)等等。
emptyframe = data.frame(num = numeric(0), name = character(0))
a = emptyframe
b = data.frame(num = 1:2, name = paste("ID", 1:2))
c = data.frame(num = 6:8, name = paste("ID", 6:8))
d = emptyframe
x = list(a, b, c, d)
combined = lapply(x, function(x){
if(is.data.frame(x) && nrow(x)==0){
# Creating an empty data frame you'd preferably want to know before-hand what kind of variables you will have
emptyframe
}else{ # I would also cast it data.frame before returning, as it may have just failed cause of is.data.frame == FALSE
as.data.frame(x)
}
})
combined
#> combined
#[[1]]
#[1] num name
#<0 rows> (or 0-length row.names)
#
#[[2]]
# num name
#1 1 ID 1
#2 2 ID 2
#
#[[3]]
# num name
#1 6 ID 6
#2 7 ID 7
#3 8 ID 8
#
#[[4]]
#[1] num name
#<0 rows> (or 0-length row.names)
如果空data.frames是一致的,有很多奇妙的东西,那么你可以使用上面的方法,因为它们被认为是正规的data.frames做。例如,考虑将它们绑定到单个更大的数据中。行:
do.call("rbind", combined)
#> do.call("rbind", combined)
# num name
#1 1 ID 1
#2 2 ID 2
#3 6 ID 6
#4 7 ID 7
#5 8 ID 8
您还需要'else'来返回'x'如果存在多个data.frames,一个“列表” – akrun