jr134
jr134

Reputation: 83

Returned an extra printed result "[1] 36" from for loop: How to remove it?

#Create a function to print squares of numbers in sequence
squareseq <- function(a) {
   for(i in 1:a) {
      b <- i^2
      result <- print(b)
   }
   return(result)
}

# Call the function supplying 6 as an argument
squareseq(6)

The result of calling the function above, is shown below:

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
[1] 36

How do I keep "return(result)" but remove the duplicated line: "[1] 36"? So I get this result below:

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36

Upvotes: 1

Views: 91

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133610

My answer is going to be old fashion theortical here.

Problem in your approach is first you are printing values in for loop so whenever function is called it will print as per argument(all numbers). Now when function comes out of that loop you are returning the value which will return latest value of variable named result in your case, that is the actually reason only last item is being printed 2 times(because item is already printed previously and now getting returned).

As per @Roland's comments I have edited my answer now(where it was saying do not return anything in function, seems to be not applicable with R). Since it is mandatory to return a value in R so pleaseuse @DiceboyT's nice solution using invisible.

Upvotes: 3

dave-edison
dave-edison

Reputation: 3736

Use invisible:

squareseq <- function(a) {
  for(i in 1:a) {
    b <- i^2
    result <- print(b)
  }
  invisible(result)
}

squareseq(6)
#[1] 1
#[1] 4
#[1] 9
#[1] 16
#[1] 25
#[1] 36

Upvotes: 3

Related Questions