Home > front end >  Delete all elements of R list that are character
Delete all elements of R list that are character

Time:07-06

I have a list in R that looks like this:

> a = seq(1,10,2)
> b = 'test'
> c = seq(1,3,1)
> d = 'another test'
> 
> ls = list(a,b,c,d)
> 
> ls
[[1]]
[1] 1 3 5 7 9

[[2]]
[1] "test"

[[3]]
[1] 1 2 3

[[4]]
[1] "another test"

Is there a way to delete all list elements that are characters? So, the result would look like this:

[[1]]
[1] 1 3 5 7 9

[[2]]
[1] 1 2 3

CodePudding user response:

Not a good idea to call your list ls. It messes up with function ls. I call it lst below.

lst <- list(c(1, 3, 5, 7, 9), "test", c(1, 2, 3), "another test")

We can do

lst[!sapply(lst, is.character)]
#[[1]]
#[1] 1 3 5 7 9
#
#[[2]]
#[1] 1 2 3

CodePudding user response:

Or use Filter:

Filter(Negate(is.character), ls)

Output:

[[1]]
[1] 1 3 5 7 9

[[2]]
[1] 1 2 3

CodePudding user response:

Or use purrr's discard-function:

library(purrr)
discard(ls, is.character)
  • Related