简体   繁体   English

如何应用依赖于 R 中三个变量的 function?

[英]How to apply a function that depends on three variables in R?

Im sure a question like this has been asked before.我敢肯定以前有人问过这样的问题。 But Im struggling to find an answer (and to even word the question clearly).但我努力寻找答案(甚至清楚地表达这个问题)。

If I have 2 variables, I want to apply a function to each pair of these variables, where the function depends on a third variable.如果我有 2 个变量,我想将 function 应用于每对这些变量,其中 function 取决于第三个变量。 For example,例如,

If I have some data that looks like this:如果我有一些看起来像这样的数据:

x <- c(1:4)
y <- c(1,2)
n <- seq(1,200, length.out = 100)

Now, imagine I want to apply rnorm to each of the pairs of x and y , where y would be my mean and x would be the standard deviation.现在,假设我想将rnorm应用于每对xy ,其中y是我的平均值, x是标准差。 But I want to loop through each of these pairs where each value of n would be my number of observations.但是我想遍历这些对中的每一对,其中n的每个值都是我的观察次数。

So for example, I was trying a nested loop... the below example doesn't work, but I hope it illustrates what Im trying to achieve:例如,我正在尝试一个嵌套循环......下面的例子不起作用,但我希望它说明了我试图实现的目标:

for(i in 1:2){
  for(j in 1:4){
    for(k in 1:length(n)){
    ans[] <- rnorm(n[k], y[i], x[j])
    }
  }
}

Any suggestions as to how I could achieve this?关于我如何实现这一目标的任何建议?

using expand.grid使用 expand.grid

z = expand.grid(n,x,y)
apply(z, 1, function(i) rnorm(i[1], i[2], i[3]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM