Ifelse statement to add NA to list

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Ifelse statement to add NA to list



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.


ifelse


NA



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


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





How is this different from your previous question: stackoverflow.com/questions/51732416/…?
– Lamia
Aug 10 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 at 18:52


length<-




3 Answers
3


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))



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



We can use stri_list2matrix from stringi


stri_list2matrix


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


ex <- list(c(35, 61), c(2, 11, 13), c(10, 15, 35), c(35, 44, 78), c(22, 86, 101))






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard