Is there any way in R to keep the index number same as before, while removing NULL and character[0] element from list. For example:
ld:
[[1]]
[1]"D2HGDH"
[[2]]
character(0)
[[3]]
character(0)
[[4]]
[1] "TNF" "IL6" "CXCL1"
[[5]]
character(0)
[[6]]
character(0)
[[7]]
[1] "ICAM1"
[[8]]
NULL
Than removing NULL and character[0] using the following code.
#remove character 0 element
rmchar <- lapply(seq(ld) , function(x) ld[[x]][!ld[[x]] == "character(0)" ])
# remove null
is.NullOb <- function(x) if(!(is.function(x))) is.null(x) | all(sapply(x, is.null)) else FALSE
rmNullObs <- function(x) {
x <- Filter(Negate(is.NullOb), x)
lapply(x, function(x) if (is.list(x)) rmNullObs(x) else x)
}
rmnull <- rmNullObs(rmchar)
so after running this the index is changed like:
[[1]]
[1] "D2HGDH"
[[2]]
[1] "TNF" "IL6" "CXCL1"
[[3]]
[1] "ICAM1"
which i don't want. I want the index number same as in list ld
. So basically my desired output is looking something like:
[[1]]
[1] "D2HGDH"
[[4]]
[1] "TNF" "IL6" "CXCL1"
[[7]]
[1] "ICAM1"
Any way to do this? If yes than How?
I appreciated any help. Thank You.