Laura
Laura

Reputation: 483

Loop with 2 different Indexes in R

I create a list called list_ok:

 list_ok <- list()
 a=c(1,2,3,4,5)
 b=c(6,7,8,9,10)
 c=c(11,12,13,14,15)
 d=c(16, 17, 18, 19, 20)
 e=c(21,22,23,24,25)

 list_ok[[1]]=a
 list_ok[[2]]=b
 list_ok[[3]]=c
 list_ok[[4]]=d
 list_ok[[5]]=e

I want to recreate the list list_ok using this for below. Its weird but this idea I will use to another exercise which is much bigger than this:

new_list <- list()

for (i in 1:5) {
  for(k in 1:5) {     
    new_list <- list_ok[[i]][[k]]
  }
}

The biggest problem I am facing is to know how to handle with two different index i and k. How do you handle with this?

Also I have been thinking about lapply function but it didnt work.

Any help?

Upvotes: 0

Views: 2459

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61154

Try this, first create an object new_list to allocate values, then use [ and each indices i and k in new_list[[i]][k] to populate new_list with those values extracted from list_ok[[i]][[k]]

new_list <- vector(mode = "list", length=5)

for (i in 1:5) {
  for(k in 1:5) {     
    new_list[[i]][k] <- list_ok[[i]][k]
  }
}

> new_list
[[1]]
[1] 1 2 3 4 5

[[2]]
[1]  6  7  8  9 10

[[3]]
[1] 11 12 13 14 15

[[4]]
[1] 16 17 18 19 20

[[5]]
[1] 21 22 23 24 25

Upvotes: 1

lebatsnok
lebatsnok

Reputation: 6449

I don't know what you're after but instead of nested loops, I'd use lapply and : here:

 lapply(seq(1,21,5), function(x) x:(x+4))
 # alternatively: lapply(seq(1,21,5), seq, length.out=5)

 # or with names:
 setNames(lapply(seq(1,21,5), function(x) x:(x+4)), letters[1:5])

 # output:

$a
[1] 1 2 3 4 5

$b
[1]  6  7  8  9 10

$c
[1] 11 12 13 14 15

$d
[1] 16 17 18 19 20

$e
[1] 21 22 23 24 25

Upvotes: 0

Related Questions