I have two list of GGPLOT objects (charts):
SD
$NCED3 - DN7756_c0_g1
$SVP - DN2362_c0_g1
$PYL4 - DN76611_c0_g1
$PYL10 - DN5056_c0_g1
$ICE1 - DN3803_c1_g5
$AHG3 - DN4648_c0_g1
$ABF2 - DN1262_c0_g3
$ABI3 - DN3814_c0_g1
and
LD
$NCED3 - DN16845_c3_g1
$SVP - DN16025_c2_g1
$PYL4 - DN6782_c0_g1
$PYL10 - DN17323_c1_g1
$ICE1 - DN16653_c3_g1
$AHG3 - DN17323_c2_g6
$ABF2 - DN16572_c0_g1
$ABI3 - DN16033_c4_g1
I want to merge both lists in one, but I need to alternate elements from both lists (notice that the name of the entries for both lists coincide at the same list positions). As far, it works as follows:
plot_list <- list(LD[[1]], SD[[1]], LD[[2]], SD[[2]], LD[[3]], SD[[3]],LD[[4]], SD[[4]], LD[[5]], SD[[5]], LD[[6]], SD[[6]], LD[[7]], SD[[7]], LD[[8]], SD[[8]])
However I need a new syntax because I need to use the script on several list of different lengths. There is a way to get the list without calling the elements one by one?
CodePudding user response:
You can use cbind
then t
and finaly unlist
.
x <- list(sd = list(a=1, b=2, c=3), ld = list(a=4, b=5, c=6))
unlist(t(do.call(cbind, x)))
#do.call(cbind, x) |> t() |> unlist() #Alternative
#[1] 1 4 2 5 3 6
In case there are different types:
unlist(asplit(do.call(cbind, x), 1), FALSE, FALSE)
CodePudding user response:
We may use transpose
from purrr
library(purrr)
library(dplyr)
transpose(x) %>%
unlist(use.names = FALSE)
#[1] 1 4 2 5 3 6
Or in base R
unlist(do.call(Map, c(f = c, x)), use.names = FALSE)
[1] 1 4 2 5 3 6
data
x <- list(sd = list(a=1, b=2, c=3), ld = list(a=4, b=5, c=6))