Search code examples
rlistvectordefault

Defining nested list into a vector with default R packages


myList <- rep(0, 5)
myList <- list('Aa'= c("1","12"), 'Ba'= c("123","321"), 'Ca'= c("444"))
for (x in names(myList)) {
  for (j in myList[x]) {
    sample <- c(unlist(myList[j]))
  } }

sample

In a nested list, want to turn this list to a vector with the

"for"

loop

I can't figure out how to extract the values without defining a function.

sample <- c(unlist(myList[x])

Doing "unlist" does the work just with another codes

> sample
 NULL

But I want all and this one is not working like that. Is there any basic version? No need to be fast or non-complicate. Just with only the base R distribution packages, with the

alternative of "unlist"

if it is possible.

I need something like

     Aa1  Aa2  Ba1  Ba2  Ca1  
     "1" "12" "123" "444"

And i think i don't need

myList <- rep(0, 5)


Solution

  • If I'm understanding you right you want to unlist without unlist in base R. You could do it like so:

    res <- NULL
    for (i in seq(names(myList))) {
      nm <- names(myList)[i]
      l <- myList[[nm]]
      res<- c(res, setNames(l, paste0(nm, seq(l))))
    }
    res
    # Aa1   Aa2   Ba1   Ba2   Ca1 
    # "1"  "12" "123" "321" "444" 
    

    Check:

    unlist(myList)
    # Aa1   Aa2   Ba1   Ba2    Ca 
    # "1"  "12" "123" "321" "444"