Reputation: 83
#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
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
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