How to delete several elements from a list() at once in R?

Asked

Viewed 39 times

3

I have the following list:

x <- list("1", 1, 2, 2.1, TRUE, "yes", "necessary", 31, FALSE, "FALSE")

would like to exclude from it all the elements which NAY are whole numbers and not characters, in which case the elements which are in heading [4], [5] and [9] I’ve tried to make:

x <- x[-4][-5][-9]

however only the first element is removed correctly, so that the index of each later element is changed with the one removed from the first, the list is:

[[1]]
[1] "1"

[[2]]
[1] 1

[[3]]
[1] 2

[[4]]
[1] TRUE

[[5]]
[1] "necessary"

[[6]]
[1] 31

[[7]]
[1] FALSE

[[8]]
[1] "FALSE"

how to remove the items from position [4], [5] and [9] without changing the index of unwanted items?

  • 3

    Try it like this x2 = x[c(-4,-5,-9)]

1 answer

4


To remove exactly positions 4, 5 and 9, just inform a vector with these positions to the list:

x <- list("1", 1, 2, 2.1, TRUE, "yes", "necessary", 31, FALSE, "FALSE")

x[-c(4, 5, 9)]
#> [[1]]
#> [1] "1"
#> 
#> [[2]]
#> [1] 1
#> 
#> [[3]]
#> [1] 2
#> 
#> [[4]]
#> [1] "yes"
#> 
#> [[5]]
#> [1] "necessary"
#> 
#> [[6]]
#> [1] 31
#> 
#> [[7]]
#> [1] "FALSE"

But if you want something more general that fits any situation where you want to delete from a list all elements that are not integer numbers or characters, use the solution below.

The function testar.inteiro checks that each element in the list is defined only as a number without a decimal part.

testar.inteiro <- function(x){
  !grepl("[^[:digit:]]", format(x, digits = options()$digits, scientific = FALSE))
}

x[!(!sapply(x, is.character) & !sapply(x, testar.inteiro))]
#> [[1]]
#> [1] "1"
#> 
#> [[2]]
#> [1] 1
#> 
#> [[3]]
#> [1] 2
#> 
#> [[4]]
#> [1] "yes"
#> 
#> [[5]]
#> [1] "necessary"
#> 
#> [[6]]
#> [1] 31
#> 
#> [[7]]
#> [1] "FALSE"

Note that in the original example, the first element of the list is "1", that for R is not an integer number. That is a character. However, the function testar.inteiro keeps this element in the list, because the question asked for it in its expected result,.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.