Home > Back-end >  How can I remove an element from a list by index, when the index matches a value from another list?
How can I remove an element from a list by index, when the index matches a value from another list?

Time:10-30

I have a list (list_a) with values and I want to remove all values from that list that have a certain index. To do this I already have a separate list (list_b) that has all the indexes that I want to remove as its values. Now I want to remove from list_a all the values that have an index that matches a value from list_b.

To make it easy to understand here is an example:

list_a <- list("One", "Two", "Three", "Four", "Five") # original list

list_b <- list(2, 4) # indexes that I want to remove from list_a

# Desired Output:
# [1] "One" "Three" "Five" 

I tried doing the following:

list_c <- list_a[-c(list_b)]
# But got the following error:
# Error : invalid argument to unary operator

Because I know that I can remove the indexes in the following manner:

list_c <- list_a[-c(2,4)]

But I don't want to know the values that I want to remove beforehand, can't I use a list as an argument to remove indexes of another list?

CodePudding user response:

You can’t index using a list; you need to use an atomic vector. You can solve your issue by

  1. Creating list_b as a numeric vector to begin with:
list_b <- c(2, 4)
list_a[list_b]
  1. Or converting to an atomic vector using as.numeric() or unlist().
# either
list_a[as.numeric(list_b)]
# or
list_a[unlist(list_b)]
  • Related