为什么“apply”会折叠零长度向量列表以及如何防止它?

问题描述 投票:0回答:1

我不知道这来自 the inferno 的哪一圈,但是

apply
返回值类型/格式发生变化,当且仅当 all 中的元素长度为零:

MWE

M0 = matrix(0,10,3)
M1 = M0
M1[1,1] = 1 # M1 differs from M0 by exactly 1 non-zero value
apply(M0,2,rep.int,x=1:10) # integer(0) <- undesired result
apply(M1,2,rep.int,x=1:10) # list(1,integer(0),integer(0)) <- desired result

M0
的期望结果是
list(integer(0),integer(0),integer(0))

问题

  • 为什么会有这种行为?
  • 我怎样才能得到
    M0
    上的结果来匹配
    M1

我目前正在编写一个包装器,因为

apply
没有任何像
sapply
这样的“简化”参数。

r
1个回答
0
投票

只是不要

simplify

> apply(M0, 2, myrep.int, x=1:10, simplify=FALSE)
[[1]]
integer(0)

[[2]]
integer(0)

[[3]]
integer(0)
© www.soinside.com 2019 - 2024. All rights reserved.