Home > Back-end >  R: Within List of Lists, Reverse Each List Order
R: Within List of Lists, Reverse Each List Order

Time:08-25

I have a list of lists. I want to reverse the order of the elements within each list. I am using this within a for loop, but I've provided a simplified example below.

r1 = c(1,2,3)
r2 = c(4,5,6)
r3 = c(7,8,9)

all <- list(Rep1 = as.list(r1),
            Rep2 = as.list(r2),
            Rep3 = as.list(r3))

rev(all) reverses the order of the individual lists but retains the order the list elements.

I've also tried to apply rev() during list assembly, but for my purposes this requires an ifelse statement. For some reason this results in only returning the first element of each list.

Strand = " "

allrev <- list(
  Rep1 = ifelse(Strand == " ", as.list(r1), rev(as.list(r1))),
  Rep2 = ifelse(Strand == " ", as.list(r2), rev(as.list(r2))),
  Rep3 = ifelse(Strand == " ", as.list(r3), rev(as.list(r3)))
)
> allrev
$Rep1
$Rep1[[1]]
[1] 1


$Rep2
$Rep2[[1]]
[1] 4


$Rep3
$Rep3[[1]]
[1] 7

Desired Output

all_rev <- list(
  Rep1 = as.list(c(3,2,1)),
  Rep2 = as.list(c(6,5,4)),
  Rep3 = as.list(c(9,8,7))
  )

Solution (Method Suggested by Gregor)

Strand = "-"
all_rev <- list(
  Rep1 = if(Strand == " ") as.list(r1) else rev(as.list(r1)),
  Rep2 = if(Strand == " ") as.list(r2) else rev(as.list(r2)),
  Rep3 = if(Strand == " ") as.list(r3) else rev(as.list(r3))
  )

> all_rev
$Rep1
$Rep1[[1]]
[1] 3

$Rep1[[2]]
[1] 2

$Rep1[[3]]
[1] 1


$Rep2
$Rep2[[1]]
[1] 6

$Rep2[[2]]
[1] 5

$Rep2[[3]]
[1] 4


$Rep3
$Rep3[[1]]
[1] 9

$Rep3[[2]]
[1] 8

$Rep3[[3]]
[1] 7

CodePudding user response:

You want to apply the function rev to each list item:

solution <- lapply(all, rev)
identical(solution, all_rev)
# [1] TRUE

You can, of course, make this conditional using if():

if(Strand == " ") {
  all <- lapply(all, rev)
}

If you don't like lapply, you can also use a for loop:

if(Strand == " ") {
  for(i in seq_along(all)) {
    all[[i]] <- rev(all[[i]])
  }
}
  • Related