gpt4 book ai didi

r - 有关使用external()和用户定义的函数的简单问题?

转载 作者:行者123 更新时间:2023-12-03 14:03:33 24 4
gpt4 key购买 nike

> fun1 <- function(x,y){x+y}
> outer(seq(1,5,length=5),seq(6,10,length=5),fun1)
[,1] [,2] [,3] [,4] [,5]
[1,] 7 8 9 10 11
[2,] 8 9 10 11 12
[3,] 9 10 11 12 13
[4,] 10 11 12 13 14
[5,] 11 12 13 14 15
> fun2 <- function(x,y){z<-c(x,y);z[1]+z[2]}
> outer(seq(1,5,length=5),seq(6,10,length=5),fun2)
Error in dim(robj) <- c(dX, dY) :
dims [product 25] do not match the length of object [1]


为什么fun2()不起作用? fun2()和fun1()本质上不是同一件事吗?

最佳答案

如果您阅读?outer,答案将变得显而易见:

Details:

‘X’ and ‘Y’ must be suitable arguments for ‘FUN’. Each will be
extended by ‘rep’ to length the products of the lengths of ‘X’ and
‘Y’ before ‘FUN’ is called.

‘FUN’ is called with these two extended vectors as arguments.
Therefore, it must be a vectorized function (or the name of one),
expecting at least two arguments.


考虑一下您在做什么,您正在将两个向量串联为一个向量,然后将这个向量的第一个和第二个元素相加。另一方面, fun1()对输入进行矢量化求和,因此返回的对象的长度与输入的各个长度相同。在 fun2()中,输出是长度为1的向量,预计为25。

实现 fun2()背后的想法的方法是 cbind()而不是 c()这两个输入:

> fun3 <- function(x, y) { z <- cbind(x, y); z[,1] + z[,2]}
> outer(seq(1,5,length=5),seq(6,10,length=5),fun3)
[,1] [,2] [,3] [,4] [,5]
[1,] 7 8 9 10 11
[2,] 8 9 10 11 12
[3,] 9 10 11 12 13
[4,] 10 11 12 13 14
[5,] 11 12 13 14 15

关于r - 有关使用external()和用户定义的函数的简单问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5554305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com