Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 防止sapply返回3D阵列_R_Sapply - Fatal编程技术网

R 防止sapply返回3D阵列

R 防止sapply返回3D阵列,r,sapply,R,Sapply,如果我使用sapply对参数向量应用函数,并且该函数返回data.frame,则输出似乎简化为3D数组 例如: set.seed(42) fn <- function(i) data.frame(n=i, x=rnorm(2, i+2)) sapply(1:10, fn) > [,1] [,2] [,3] [,4] ... > n Integer,2 Integer,2 Integer,2 Integer,2 ... &

如果我使用
sapply
对参数向量应用函数,并且该函数返回data.frame,则输出似乎简化为3D数组

例如:

set.seed(42)
fn <- function(i) data.frame(n=i, x=rnorm(2, i+2))
sapply(1:10, fn)
>   [,1]      [,2]      [,3]      [,4]       ...     
> n Integer,2 Integer,2 Integer,2 Integer,2  ...
> x Numeric,2 Numeric,2 Numeric,2 Numeric,2  ...
如果I
Vectorize()
。有没有一种方法可以避免在创建data.frame列表并将其重新绑定时的开销


我觉得我遗漏了一些明显的东西,但是
s/l/vapply
(和
simplify2array
)似乎记录得非常简洁。

您认为这种方法如何:

fn <- function(i) c(i, x=rnorm(n=1, i+2))
data.frame(t(sapply(rep(1:10,each=2), fn)))

fn好的,拿23或类似的,这里有一个选项,允许您保持函数不变。不幸的是,这会将所有内容强制为数字,这对您的应用程序来说应该没问题:

mx <- matrix(
  unlist(sapply(1:10, fn))[unlist(lapply(1:4, seq, by=4, len=10))], 
  ncol=2
)
as.data.frame(mx[order(mx[, 1]), ])

mx谢谢你没想到。理想情况下,可以让(real)函数在内部处理data.frames时保持原样,但如果没有更好的方法,则可以接受。也许您可以使用
restrape()
对format=“long”执行此操作
mx <- matrix(
  unlist(sapply(1:10, fn))[unlist(lapply(1:4, seq, by=4, len=10))], 
  ncol=2
)
as.data.frame(mx[order(mx[, 1]), ])