【问题标题】:why sapply() and tapply() have the same result, but not identical?为什么 sapply() 和 tapply() 有相同的结果,但不完全相同?
【发布时间】:2015-04-11 01:07:17
【问题描述】:

这是我的代码

pulse <- round(rnorm(22, 70, 10 / 3)) + rep(c(0, 5), c(10, 12))
group <- rep(c("A", "B"), c(10, 12))

tapply(pulse, group, length)

A  B 
10 12

list<-split(pulse,group)
sapply(list,length)

A  B 
10 12
identical(tapply(pulse, group, length),sapply(list,length))#FALSE
identical(tapply(pulse, group, length),as.table(sapply(list,length)))#FALSE
identical(tapply(pulse, group, length),as.vector(sapply(list,length)))#FALSE
identical(as.table(tapply(pulse, group, length)),as.table(sapply(list,length)))#TRUE

这两个函数产生相同的结果,但为什么它们不一样?我在 R 中使用了 typeof(),看来这两个结果的类型都是“double”。

为什么相同(tapply(脉冲,组,长度),sapply(列表,长度))是假的?如何调整我的代码以使它们相同?

谢谢。

【问题讨论】:

  • 如果检查每个输出的dput,一个具有.Names 属性,而另一个是.Dimnames。通过删除属性,它将是相同的......即。 `完全相同(as.vector(r1), as.vector(r2))# [1] TRUE`其中v1、v2是tapplysapply的输出。或者更改属性,即attributes(r1) &lt;- attributes(r2); identical(r1, r2)
  • 非常感谢。原来这两种方法有不同的类。现在可以了。

标签: r sapply tapply


【解决方案1】:

如果我们检查每个输出的str

str(r1)
# int [1:2(1d)] 10 12
#- attr(*, "dimnames")=List of 1
# ..$ : chr [1:2] "A" "B"
str(r2)
# Named int [1:2] 10 12
# - attr(*, "names")= chr [1:2] "A" "B"

attributes 在它们之间是不同的。一种方法是删除每个输出的attributes,它们将是相同的

 identical(as.vector(r1), as.vector(r2))
 #[1] TRUE

但是,as.vector 也会删除 names。如果我们需要保留names 部分,请将attributes 设置为相同的输出

 attributes(r1) <- attributes(r2)
 identical(r1, r2)
 #[1] TRUE

在哪里

r1 <- tapply(pulse, group, length)
r2 <- sapply(list,length)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2021-02-12
    • 2018-02-17
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多