0

I am running into an issue turning my list into an array for further analysis due to the different number of values within the strings as such:

[[1]]
[1] 35 61
[[2]]
[1]  2 11 13
[[3]]
[1] 10 15 35
[[4]]
[1] 35 44 78
[[5]]
[1]  22  86 101

Due to the fact that I have 2 integers in some strings and 3 in other strings, I am unable to turn it into an array.

Ultimately, I would like to create an ifelse statement to insert an NA into the into the list when there are only two integers.

This is the statement I made:

length = length(list_i1)

list_i1 = ifelse(list_i1[[1:length]][3] != 0:Inf, 
                 list_i1[[1:length]][3] == "NA",
                 list_i1[[1:length]][3] == list_i1[[1:length]][3])

It is returning: Error in list_i1[[1:length]] : recursive indexing failed at level 2

E. Sas
  • 45
  • 5
  • 1
    How is this different from your previous question: https://stackoverflow.com/questions/51732416/create-an-array-from-a-list-with-different-number-of-outputs-for-each-value? – Lamia Aug 10 '18 at 15:53
  • For various reasons I was hoping to use an ifelse statement rather than something like: list_i1 = t(sapply(list_i1,`length<-`,max(lengths(list_i1)))). I had written other parts of my script to fit in with the results from the array I would have ideally gotten from the ifelse statement. – E. Sas Aug 10 '18 at 18:52

3 Answers3

2
t(sapply(list_i1,`length<-`,max(lengths(list_i1))))
     [,1] [,2] [,3]
[1,]   35   61   NA
[2,]    2   11   13
[3,]   10   15   35
[4,]   35   44   78
[5,]   22   86  101

where

list_i1 = list(c(35,61),c(2,11,13),c(10,15,35),c(35,44,78),c(22,86,101))
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

Try the following

ex <- list(c(35, 61), c(2, 11, 13), c(10, 15, 35), c(35, 44, 78), c(22, 86, 101))
max_len <- max(lengths(ex))
mapply(function(x, y) c(x, rep(NA, max_len - y)), ex, lengths(ex))

#      [,1] [,2] [,3] [,4] [,5]
# [1,]   35    2   10   35   22
# [2,]   61   11   15   44   86
# [3,]   NA   13   35   78  101
CPak
  • 13,260
  • 3
  • 30
  • 48
0

We can use stri_list2matrix from stringi

library(stringi)
m1 <-  stri_list2matrix(ex, byrow = TRUE)
`dim<-`(as.numeric(m1), dim(m1))
#      [,1] [,2] [,3]
#[1,]   35   61   NA
#[2,]    2   11   13
#[3,]   10   15   35
#[4,]   35   44   78
#[5,]   22   86  101

data

ex <- list(c(35, 61), c(2, 11, 13), c(10, 15, 35), c(35, 44, 78), c(22, 86, 101))
akrun
  • 874,273
  • 37
  • 540
  • 662