Search code examples
rfor-loopmclapply

How do I convert "for" in "mclapply"?


I have this:

# A simple "script" that receives an index
  ScriptR = function(i) {
    A = i^3;
  };

# With "for", pass the index "i" for "ScriptR"
  for (i in 1:10) {
     ScriptR(i);
  }; 

# How do I pass the index "i" for "ScriptR" function ??
  mclapply(1:10, ScriptR, mc.set.seed = FALSE);

How do I pass the index "i" for "ScriptR" function ??

Tks


Solution

  • Your code should work just fine. Since your function ScriptR has only one argument (that is, i), when you call mclapply(1:10, ScriptR, mc.set.seed = FALSE) the numbers 1:10 are being passed as arguments to ScriptR. If you want to be more explicit, you could call mclapply(1:10, function(i) ScriptR(i), mc.set.seed = FALSE) but in this case there is really no need for that.