Reputation: 65
my for loop should execute every 50th time in time period of 1000, in matlab there is something like this 1:50:1000 do we have anything simimlar in R? please let me know starting at one with increments of 50 until 1000
Upvotes: 2
Views: 2382
Reputation: 21471
EDIT - Possibly the cleanest solution using apply
(no loop):
apply(stored[seq(1,1000,50), ], 1, yourfunction)
# where 1 indicates over rows.
Using modulo (loop)
My usual way of doing things is using modulo to get the required behavior. For example, print the iteration every 50 iterations while doing some action on every iteration:
stored <- 1:1000
for (i in 1:1000) {
stored[i] <- rnorm(1)
if (i %% 50 == 0) { print(i) }
}
This will allow full control, as you can also do other stuff every, say 100 iterations by adding another if i modulo x == 0, then ...
The problem with the sequence method is that you cannot store efficiently in a loop:
stored <- 1:1000
for (i in seq(0,1000,by=50)) {
stored[i] <- rnorm(1)
print(i)
}
The printing will be fine, but the resulting vector will be:
[1] NA NA NA NA NA NA
[7] NA NA NA NA NA NA
[13] NA NA NA NA NA NA
[19] NA NA NA NA NA NA
[25] NA NA NA NA NA NA
[31] NA NA NA NA NA NA
[37] NA NA NA NA NA NA
[43] NA NA NA NA NA NA
[49] NA -0.73339457 .... ... ... etc
To solve this, you also have to do some dividing, so I found it to be most efficient to just use a normal loop and then use modulo to have perfect control.
Using sapply
(no loop)
As you pointed out in your comment, you want to actually store something, and for that a loop over a sequence will leave you with holes. So you can use sapply
(for apply family documentation, read this)
Normally, one could use sapply(1:1000, function(x) mean(stored[x,]))
, where the function could be anything. If you want for every iteration, there are shortcuts like colMeans.
However, since you want a sequence, you can use sapply
, and feed it a variable argument.
seqMean <- function(x) {
mean(stored[x,])
}
sapply(seq(1,1000,50), function(x) seqMean(x))
or in short:
sapply(seq(1,1000,50), seqMean)
Upvotes: 1
Reputation: 49063
There's a by
argument to the seq
function :
R> seq(0,1000,by=50)
[1] 0 50 100 150 200 250 300 350 400 450 500 550 600 650
[15] 700 750 800 850 900 950 1000
So you can use :
R> for (i in seq(0,1000,by=50)) print(i)
[1] 0
[1] 50
[1] 100
[1] 150
[1] 200
[1] 250
[1] 300
[1] 350
[1] 400
[1] 450
[1] 500
[1] 550
[1] 600
[1] 650
[1] 700
[1] 750
[1] 800
[1] 850
[1] 900
[1] 950
[1] 1000
Upvotes: 3