How can I use the for loop with special seq

Viewed 178

I want to make a for loop where the seq is an array's elements.

So like I have an array like this:

int <- array(c(30,60,150,300,450,1500))

and I wanted that the first j is 30, second is 60 ...etc.

But when I obviosly tried this:

for (j in int)

this did not work.

How can I solve this?

3 Answers

We could use embed

m1 <- embed(c(int, int), length(int))[seq_along(int),]
m1[lower.tri(m1)] <- NA
lapply(asplit(m1, 1), function(x) rev(x[!is.na(x)]))
#[[1]]
#[1]   30   60  150  300  450 1500

#[[2]]
#[1]   60  150  300  450 1500

#[[3]]
#[1]  150  300  450 1500

#[[4]]
#[1]  300  450 1500

#[[5]]
#[1]  450 1500

#[[6]]
#[1] 1500

Or using a for loop

out <- vector('list', length(int))
for(i in seq_along(int)) out[[i]] <- if(i == 1) int else int[-seq(i -1)]

Are you looking for this?

Map(function(x) int[x:length(int)], seq(int))
# [[1]]
# [1]   30   60  150  300  450 1500
# 
# [[2]]
# [1]   60  150  300  450 1500
# 
# [[3]]
# [1]  150  300  450 1500
# 
# [[4]]
# [1]  300  450 1500
# 
# [[5]]
# [1]  450 1500
# 
# [[6]]
# [1] 1500

Or this

Map(function(x) int[x:length(int)], 1:3)
# [[1]]
# [1]   30   60  150  300  450 1500
# 
# [[2]]
# [1]   60  150  300  450 1500
# 
# [[3]]
# [1]  150  300  450 1500

Anyway, the second argument of Map are the starting indices.

Another base R option

> lapply(-seq_along(int), tail, x = c(NA, int))
[[1]]
[1]   30   60  150  300  450 1500

[[2]]
[1]   60  150  300  450 1500

[[3]]
[1]  150  300  450 1500

[[4]]
[1]  300  450 1500

[[5]]
[1]  450 1500

[[6]]
[1] 1500
Related