【问题标题】:Unexpected results from ifelse来自 ifelse 的意外结果
【发布时间】:2017-12-15 00:40:01
【问题描述】:

我从 ifelse 函数中得到了意想不到的结果:

vector <- factor(c('x', 'x', 'y', 'z'), levels = c('x', 'y', 'z'))
ifelse(class(vector) == "factor", yes = levels(vector), no =
unique(vector)) # Returns character "x" and not the expected c("x", "y",
"z")

# Manual debug
class(vector) == "factor" # TRUE
levels(vector) # [1] "x" "y" "z"

知道发生了什么吗?

【问题讨论】:

  • 你需要if,即if(is.factor(vector)){levels(vector)}else{unique(vector)}
  • ?ifelse我们可以得知,它返回的值是一个长度和属性(包括维度和“类”)与测试值和数据值相同的向量。是或否
  • 一个矫枉过正的选择:从 perl 中借用 // 并执行类似 levels(x) // unique(x)... 在实践中:`%//%` = function(x,y) if (!is.null(x)) x else y; levels(x) %//% unique(x) stackoverflow.com/questions/23873379/…
  • 另一个稍微有点矫枉过正的选项,但 ifelse 是:unlist(ifelse(class(vector) == "factor", list((levels(vector))), list(unique(vector))))。你更改ifelse 以返回一个包含一个元素的列表,然后你 unlist

标签: r


【解决方案1】:

我认为您只想使用if 语句。不是ifelse()。后者旨在使用向量并返回长度等于输入的向量。如果你想为不同的条件返回不同数量的元素,只需使用if

vector <- factor(c('x', 'x', 'y', 'z'), levels = c('x', 'y', 'z'))
xx <- if(class(vector) == "factor") levels(vector) else unique(vector)
xx

【讨论】:

    猜你喜欢
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2015-11-02
    相关资源
    最近更新 更多