防止取消列表删除NULL值 [英] Prevent unlist to drop NULL values
问题描述
我有一个列表向量,并且在它们上使用了unlist
.向量中的某些元素是NULL
,而unlist
似乎正在删除它们.
I have a vector of lists and I use unlist
on them. Some of the elements in the vectors are NULL
and unlist
seems to be dropping them.
如何防止这种情况?
这是一个简单的(非)工作示例,显示了unlist
Here's a simple (non) working example showing this unwanted feature of unlist
a = c(list("p1"=2, "p2"=5),
list("p1"=3, "p2"=4),
list("p1"=NULL, "p2"=NULL),
list("p1"=4, "p2"=5))
unlist(a)
p1 p2 p1 p2 p1 p2
2 5 3 4 4 5
推荐答案
此处的问题是,向量中间不能包含NULL
.例如:
The issue here is that you can't have NULL
in the middle of a vector. For example:
> c(1,NULL,3)
[1] 1 3
虽然中间可以有NA.您可以将其转换为字符,然后再转换为数字,这会自动将NULL值转换为NA(带有警告):
You can have NA in the middle though. You could could convert it to character and then back to numeric, which automatically converts the NULL values to NA (with a warning):
> b <- as.numeric(as.character(a))
Warning message:
NAs introduced by coercion
然后重新输入名称,因为先前的操作已将其删除:
then put the names back in, because they've been dropped by the previous operation:
> names(b) <- names(a)
> b
p1 p2 p1 p2 p1 p2 p1 p2
2 5 3 4 NA NA 4 5 `
这篇关于防止取消列表删除NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!