3

I have a list which looks like this:

[[1]]
[1] -3

[[2]]
[1] 0 0

[[3]]
[1]   6 -36  54

I want to create a vector from this which looks like

3 -36 54

To do this I have considered to add zeroes at the end of the elements, just enough to make the elements of equal size and to use

Reduce('+',....)

to paste the elements together. However, I do not want to add a superfluous amount of zeroes. The list mentioned is not necessary the list for which I want this. I have multiple lists. Finally my question is: Is there a way to retrieve the largest length of the element from a list?

pogibas
  • 27,303
  • 19
  • 84
  • 117
Cardinal
  • 208
  • 2
  • 13
  • 1
    I'm having a hard time understanding this, but I *think* I can follow some of the answers. Do you want to approximate a matrix, i.e that's what you mean about adding zeroes at the end? – camille Dec 12 '18 at 15:48

3 Answers3

2

We get the length of the individual elements of the list with lengths, then get the max value of it with max, create a logical index and subset the list

i1 <-  max(lengths(lst))
i2 <- lengths(lst)== i1
lst[i2]

Assuming the OP wanted the vector as described in the post

f1 <- function(listA, i = 1) {
   i1 <- max(lengths(listA))
   listB <- lapply(listA, `length<-`, i1)
   Reduce(`+`, lapply(listB, function(x) replace(x, is.na(x), 0)))


   }

f1(lst)
#[1]   3 -36  54

If we need it in a matrix, it can be done with stri_list2matrix and get the sum with rowSums

library(stringi)
out <- stri_list2matrix(lst)
class(out) <- 'numeric'
rowSums(out, na.rm = TRUE)
#[1]   3 -36  54

data

lst <- list(-3, c(0, 0), c(6, -36, 54))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You can expand your list to a matrix filled with NA and use rowSums on it:

# Data
foo <- list(-3, c(0, 0), c(6, -36, 54))
rowSums(sapply(foo, "[", seq_len(max(lengths(foo)))), na.rm = TRUE)
[1]   3 -36  54

sapply generates matrix that uses length of longest vector in your list (seq_len(max(lengths(foo)))):

     [,1] [,2] [,3]
[1,]   -3    0    6
[2,]   NA    0  -36
[3,]   NA   NA   54
pogibas
  • 27,303
  • 19
  • 84
  • 117
0

A Reduce() solution with a helper function:

`%+na%` <- function(x, y) {
  # Originally from: # https://stackoverflow.com/a/13106770/4552295 
  ifelse(is.na(x), y, ifelse(is.na(y), x, x + y)) 
}

n <- max(lengths(lst))    
Reduce("%+na%", lapply(lst, "[", 1:n))
[1]   3 -36  54
s_baldur
  • 29,441
  • 4
  • 36
  • 69