防止 unlist 删除 NULL 值 [英] Prevent unlist to drop NULL values

查看:13
本文介绍了防止 unlist 删除 NULL 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表向量,我对它们使用 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.

我怎样才能防止这种情况发生?

How can I prevent this?

这是一个简单的(非)工作示例,显示了 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 `

这篇关于防止 unlist 删除 NULL 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆