0

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.

Screenshot of my output. The screenshot of my output after running the code

  • The point is: if you remove some elements, indexes are changed (since index is the position of an element in the list)... so basically you can't...maybe you should think to use names instead of indexes... – digEmAll Apr 19 '16 at 09:46
  • use named list elements instead. `names(myList) <- paste0("X", 1:length(mylist))` These names will be fixed – Richard Telford Apr 19 '16 at 09:49

1 Answers1

1

Similar to @Richards's comments here is a solution for your 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 the list to names 
ld <- setNames(as.list(ld), c(1:length(ld)))

Lines below copied from R Remove NULL elements from list of lists

#Remove null and character values 
is.NullOb <- function(x) is.null(x) | all(sapply(x, is.null))

## Recursively step down into list, removing all 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 get the indexes of list that were left use

names(newList)
Community
  • 1
  • 1
discipulus
  • 2,665
  • 3
  • 34
  • 51