【问题标题】:Using rows of expand.grid data frame as inputs to custom function使用 expand.grid 数据框的行作为自定义函数的输入
【发布时间】: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


【解决方案1】:

尝试将您的向量称为列表:

y=do.call(my_function,list(x))

为什么:?do.call

do.call 根据名称或函数以及要传递给它的参数列表构造并执行函数调用。

如果我使用我定义的函数运行它,例如:

do.call(rowmean,x)#of course there's an R function for that

然后:

(函数 (x) 中的错误: 未使用的参数 (Var1 = c(29, 29), Var2 = 4:5, Var3 = c(1, 1), Var4 = c(1, 1), Var5 = c(5, 5), Var6 = c(95 , 95))

使用:

do.call(rowmean,list(x))

按预期工作。唯一的测试方法是是否提供了您的功能。

【讨论】:

  • 感谢您的帮助!好吧,除非我的数据框 x 中只有 1 行,否则它不适用于我的功能。另一方面,约瑟夫用apply(x, 1, my_function) 给出的解决方案对我有用。我得到一个大向量而不是矩阵列表,但至少计算正确完成,我可以将其格式化为我喜欢的格式!是的,我不知道为什么我坚持使用 do.call
  • 我明白了,不看整个函数很难知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多