【问题标题】:R: Using the unlist() function for a list that has some elements being integer(0)?R: 使用 unlist() 函数来处理包含整数 (0) 元素的列表?
【发布时间】:2018-06-20 04:33:32
【问题描述】:

在 R 中,我在列表上调用 unlist 以转换为向量。但是,我的一些列表元素是空的,因此返回 integer(0)unlist() 函数默认删除它。如何返回列表为空的具有NA 的向量?我创建了一个可重现的示例:

> ex.list <- list()
> ex.list[[1]] <- integer(0)
> ex.list[[2]] <- c(1,2,3)
> ex.list
[[1]]
integer(0)

[[2]]
[1] 1 2 3

> unlist(ex.list)
[1] 1 2 3

谢谢。

【问题讨论】:

标签: r


【解决方案1】:

一种方法是使用函数is.na&lt;-

is.na(ex.list) <- lengths(ex.list) == 0

ex.list
#[[1]]
#[1] NA
#
#[[2]]
#[1] 1 2 3

然后您将有一个NA,其中列表的长度为 0。

unlist(ex.list)
#[1] NA  1  2  3

【讨论】:

  • 虽然is.na(ex.list) 一开始会产生[1] FALSE FALSE,但为什么会这样?我错过了什么吗?长度 0 和 NA 问题在 R 中让我很困惑......
  • @Christoph - is.na&lt;- 是一个函数。在控制台输入`is.na&lt;-``is.na&lt;-.default` 看看它在做什么。
【解决方案2】:

我们可以根据list元素的length进行赋值,即如果它等于0,则赋值为NA

ex.list[lengths(ex.list)==0] <- NA
ex.list
#[[1]]
#[1] NA

#[[2]]
#[1] 1 2 3

【讨论】:

  • 当然,如果你不想改变原来的ex.list - unlist(replace(ex.list, lengths(ex.list)==0, NA)),你可以一步完成。
【解决方案3】:

你也可以试试单线

unlist(lapply(ex.list, function (x) ifelse(length (x) > 0, x, NA)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多