【发布时间】:2019-01-08 23:58:37
【问题描述】:
我有一个自定义函数,它接受一个包含 6 个变量的向量并返回一个矩阵,如下所示:
my_function <- (vect){
a=as.numeric(vect[1])
b=as.numeric(vect[2])
c=as.numeric(vect[3])
d=as.numeric(vect[4])
e=as.numeric(vect[5])
f=as.numeric(vect[6])
.
.(using other custom functions here)
.
return(matrix)
}
现在我想对我的函数进行多个输入并获取矩阵列表。为了创建我需要的所有输入,我使用了 expand.grid 函数,例如:
> x=expand.grid(29,4:5,1,1,5,95)
> x
Var1 Var2 Var3 Var4 Var5 Var6
1 29 4 1 1 5 95
2 29 5 1 1 5 95
所以现在我想将此 data.frame 的每一行作为输入传递给 my_function。我尝试了这样的 do.call 函数,但出现错误:
> y=do.call(my_function,x)
Error in (function (vect) :
unused arguments (Var1 = c(29, 29), Var2 = 4:5, Var3 = c(1, 1), Var4 =
c(1, 1), Var5 = c(5, 5), Var6 = c(95, 95))
我试图转置我的数据框 x,但我得到了同样的错误:
> y=do.call(my_function,as.data.frame(t(x)))
Error in (function (vect) :
unused arguments (V1 = c(29, 4, 1, 1, 5, 95), V2 = c(29, 5, 1, 1, 5, 95))
我当然没有正确使用 do.call 函数,但我的想法已经用完了......有什么帮助吗?
【问题讨论】:
-
我想你想要
apply(x, 1, my_function)。 1表示按行申请。 -
感谢约瑟夫,它有效!就是这么简单!
标签: r