【问题标题】:returning null using ifelse function使用 ifelse 函数返回 null
【发布时间】:2017-08-22 10:10:56
【问题描述】:

我正在尝试在 R 中使用 ifelse 返回 null。但它会引发错误消息。请有任何建议。

这是我的代码:

cntr1 <- ifelse(unlist(gregexpr("---",path_info[j], fixed = TRUE, useBytes = TRUE)) > 0, 3 * length(unlist(gregexpr("---",path_info[j], fixed = TRUE, useBytes = TRUE))),NULL )

错误信息是:

Error in ifelse(unlist(gregexpr("---", path_info[j], fixed = TRUE, useBytes = TRUE)) >  : 
  replacement has length zero In addition: Warning message:
In rep(no, length.out = length(ans)) :
  'x' is NULL so the result will be NULL

【问题讨论】:

  • 我不相信这是可能的。来自ifelse 的帮助页面,Value 部分:A vector of the same length [...] as test and data values from the values of yes or nolength(NULL) 返回零,因此您的 no 甚至无法回收。
  • 我不知道它是否真的对你有用,但也许尝试而不是返回 NULL 来返回 "NULL" 以便你的 ifelse 工作,然后做一个 eval(parse(text = ...) ) 真正得到NULL 出现?
  • 为什么还需要它返回NULL?无论如何,您不能在原子向量中使用NULLs。 NA 是 R 中缺失值的正确对象。
  • @LyzanderR 使用 NA 不会给出长度 0。

标签: r


【解决方案1】:

我想出了三种不同的方法来在类似 ifelse 的场景中返回 NULL

在这种情况下,b 应该是 NULL,而 a 是 NULL

a <- NULL
is.null(a)  #TRUE

b <- switch(is.null(a)+1,"notNullHihi",NULL)
b <- if(is.null(a)) NULL else {"notNullHihi"}
b <- unlist(ifelse(is.null(a),list(NULL),"notNullHihi"))

is.null(b)  #TRUE for each of them

【讨论】:

  • unlist 方法可能更烦人,因为它可以修改 FALSE 情况下的对象(例如,如果您想返回 data.frame
【解决方案2】:

我需要在我最近的一个应用程序中使用类似的功能。这就是我想出解决方案的方式。

obj <- "val1"

# Override a with null (this fails)
newobj <- ifelse(a == "val1", NULL, a)

# Separating the ifelse statement to if and else works

if(obj == "val1") newobj <- NULL else newobj <- obj

【讨论】:

    【解决方案3】:

    在您的特定情况下,ifelseyesno 是单元素向量,您可以尝试将结果作为列表返回

    ifelse(c(TRUE,FALSE,TRUE),list(1),list(NULL))
    #[[1]]
    #[1] 1
    #
    #[[2]]
    #NULL
    #
    #[[3]]
    #[1] 1
    

    如果yesno 中的任何一个是多元素列表,此方法也适用。参见例如

    x=as.list(1:3)
    y=c(as.list(letters[1:2]),list(NULL))
    ifelse(x<2,x,y)
    #[[1]]
    #[1] 1
    #
    #[[2]]
    #[1] "b"
    #
    #[[3]]
    #NULL
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 2021-03-31
      • 2016-01-30
      相关资源
      最近更新 更多