【问题标题】:Strange behavior when ordering in R在 R 中订购时的奇怪行为
【发布时间】:2018-11-07 09:08:45
【问题描述】:

我对以下代码有点迷茫:

simula <- data.frame(
  a=sample(c("b", "a"), 10, replace=TRUE), 
  b=sample(c("bb", "aa"), 10, replace=TRUE), 
  c=rnorm(10), 
  d=rnorm(10))

order(simula$a, simula$d, decreasing=c(T,F))

订单语句给出了一个错误,其中指出

参数长度不同

。这对我来说没有多大意义。

谁能解释一下为什么会报错?

【问题讨论】:

    标签: r sorting


    【解决方案1】:

    stringsAsFactors = F应该可以解决问题:

    simula <- data.frame(
      a=sample(c("b", "a"), 10, replace=TRUE), 
      b=sample(c("bb", "aa"), 10, replace=TRUE), 
      c=rnorm(10), d=rnorm(10), stringsAsFactors = FALSE)
    order(simula$a, simula$d, decreasing=c(TRUE, FALSE))
    

    否则变量将被存储为因子,样本 a / b 将只有 2 个级别,而 c / d 列有 10 个元素。

    【讨论】:

    • FALSETRUE 优于 FT。请注意,F &lt;- TRUE 是完全合法的。
    • 您的解决方案有效,但请注意order(simula$a, simula$d, decreasing=TRUE) 将在 a 和 b 为因子时有效。因此,很可能问题出在基数排序上,它是唯一接受包含多个参数的向量来表示递减的方法。
    • 非常感谢。尽管如此,使用stringsAsFactors = F 相当于在订购时使用as.character。我确实知道如何解决该错误,但我并没有真正了解导致它的原因。
    猜你喜欢
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2015-12-06
    相关资源
    最近更新 更多