Reputation: 1
I'm not a R expert but I'm trying to understand the basics of the for-loop method. I'm trying to write a for-loop that prints the output as follows:
1 3 5 7 9 11
The code I am writing is below:
for (i in 1:3) {
print(i)
print(i + 2)
}
However, I'm getting the below output based on my code:
1 3 2 4 3 5
It appears I am getting the first loop right but when it looks for i == 2
and i == 3
isn't not generating what I expect. What needs to be revised with my code so that my i == 2
and i == 3
is correct?
Upvotes: 0
Views: 225
Reputation: 42544
The OP has asked to revise his code to generate the expected result.
He has written a for
loop with 3 iterations to print 6 figures.
So, the first iteration has to print the numbers 1 and 3, the second iteration has to print the numbers 5 and 7, the third 9 and 11. Each iteration advances the output by 4.
OP's approach can be modified to return the expected result:
for (i in 1:3) {
print(4 * (i-1) + 1)
print(4 * (i-1) + 3)
}
or, less verbose
for (i in 1:3) {
print(4 * i - 3)
print(4 * i - 1)
}
[1] 1 [1] 3 [1] 5 [1] 7 [1] 9 [1] 11
Upvotes: 1
Reputation: 3269
Using the logic implemented by Edward, you can achieve the same output with sapply
:
sapply(1:6, function(i) print(i * 2 - 1))
Upvotes: 0
Reputation: 18663
I'm trying to write a for-loop that prints the output as follows:
1 3 5 7 9 11
This is one way:
for (i in 1:6) {
print(i * 2 - 1)
}
[1] 1
[1] 3
[1] 5
[1] 7
[1] 9
[1] 11
If you want to print it all on one line, then you'll have to save the results first, then print.
x <- NULL
for (i in 1:6) {
x[i] <- (i * 2 - 1)
}
print(x)
[1] 1 3 5 7 9 11
Upvotes: 2