-2

Please look at the following code in R

i=1
a1=function(x){
  print(i)
  i=i+1
  return(x^2)}
a2=replicate(5,a1(2))

I wish to have an output as 1 2 3 4 5

Can anyone help me with this? However I don't want to write for-loops. I wish to keep the replicate function as it is. Thanks for suggestions/help.

G5W
  • 36,531
  • 10
  • 47
  • 80
Sayan
  • 121
  • 4
  • 2
    You can not change the value `i` inside a function. What are you trying to do? Just print a sequence of numbers? – Psidom Jul 05 '16 at 21:22
  • Yes I wish to have a count of that. Please understand that it's a MWE – Sayan Jul 05 '16 at 21:34
  • 1
    The thing is that there are tons of ways to do that but probably not with `replicate`. `for` loop, `apply` family or `recursive` functions can all accomplish the task, but it may not be what you wanted at the end. – Psidom Jul 05 '16 at 21:36
  • 1
    to me that feels like an abuse of `replicate()` (which suggests reproducibility, consistent results, etc.). Why not use a function like `Reduce()` or `Recall()` that is better suited to this task? – baptiste Jul 05 '16 at 21:37
  • The statement of Psidom is wrong. See the answer below. If you want to learn about scoping in R I recommend this http://stackoverflow.com/questions/2628621/how-do-you-use-scoping-assignment-in-r. – Alex Jul 05 '16 at 21:38

1 Answers1

1

You can do this via global variable assignment:

i=1
a1=function(x){
  print(i)
  i<<-i+1
  return(x^2)}
a2=replicate(5,a1(2))
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5

This is not really how you should to it.

Depending on what you are really trying to do, this can work:

res <- sapply(1:5, print)
Bulat
  • 6,869
  • 1
  • 29
  • 52