Keep list index number unchanged after removing NULL and character[0] in R -
is there way in r keep index number same before, while removing null , character[0] element list. 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 , character[0] using 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 index changed like:
[[1]] [1] "d2hgdh" [[2]] [1] "tnf" "il6" "cxcl1" [[3]] [1] "icam1"
which don't want. want index number same in list ld
. desired output looking like:
[[1]] [1] "d2hgdh" [[4]] [1] "tnf" "il6" "cxcl1" [[7]] [1] "icam1"
any way this? if yes how?
i appreciated help. thank you.
similar @richards's comments here solution case
ld = list(c("d2hgdh"), character(length = 0), character(length = 0), c("tnf","il6","cxcl1"),character(length = 0), character(length = 0), c("icam1"), null) # convert list names ld <- setnames(as.list(ld), c(1:length(ld)))
lines below copied r remove null elements list of lists
#remove null , character values is.nullob <- function(x) is.null(x) | all(sapply(x, is.null)) ## recursively step down list, removing such objects rmnullobs <- function(x) { x <- filter(negate(is.nullob), x) lapply(x, function(x) if (is.list(x)) rmnullobs(x) else x) } newlist <- rmnullobs(ld)
to indexes of list left use
names(newlist)
Comments
Post a Comment