如何操作嵌套列表中的NULL元素? [英] How to manipulate NULL elements in a nested list?

查看:53
本文介绍了如何操作嵌套列表中的NULL元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含NULL元素的嵌套列表,并且我想用其他元素替换它们.例如:

I have a nested list containing NULL elements, and I'd like to replace those with something else. For example:

l <- list(
  NULL,
  1,
  list(
    2,
    NULL,
    list(
      3,
      NULL
    )
  )
)

我想用NA替换NULL元素.自然的方法是使用rapply循环遍历列表.我试过了:

I want to replace the NULL elements with NA. The natural way to do this is to recursively loop over the list using rapply. I tried:

rapply(l, function(x) NA, classes = "NULL", how = "replace")
rapply(l, function(x) if(is.null(x)) NA else x, how = "replace")

不幸的是,这两种方法都不起作用,因为rapply显然会忽略NULL元素.

Unfortunately, neither of these methods work, since rapply apparently ignores NULL elements.

如何操作嵌套列表中的NULL元素?

How can I manipulate the NULL elements in a nested list?

推荐答案

我将继续讨论使用rapply版本不会对NULL产生奇怪的行为".这是我能想到的最简单的实现:

I'm going to go with "use a version of rapply doesn't doesn't have weird behaviour with NULL". This is the simplest implementation I can think of:

simple_rapply <- function(x, fn)
{
  if(is.list(x))
  {
    lapply(x, simple_rapply, fn)
  } else
  {
    fn(x)
  }
}

(rawr::rapply2,如@rawr的评论中所述,是一种更复杂的尝试.)

(rawr::rapply2, as mentioned in the comments by @rawr is a more sophisticated attempt.)

现在我可以使用替换

simple_rapply(l, function(x) if(is.null(x)) NA else x)

这篇关于如何操作嵌套列表中的NULL元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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