Edin Mar
Edin Mar

Reputation: 121

How to delete list entry with the help of a vector?

I want to delete some list entries. The entries to be deleted are stored in delete_vector.

Example with flights:

list_flights<-dlply(flights,"carrier", function(x)subset(x, select = c(dest,air_time,flight)))
delete_vector<-c("AA","EV","VX")#should be removed from my list

I want to use delete_vector for this and not like:

list_flights$AA <- NULL

Many thanks for your help!

Upvotes: 2

Views: 36

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

We can subset the names of list and select the ones which are not present in delete_vector using %in%

new_flights <- list_flights[!names(list_flights) %in% delete_vector]

Or using setdiff

new_flights <- list_flights[setdiff(names(list_flights), delete_vector)]

Upvotes: 1

akrun
akrun

Reputation: 886948

We can use [ instead of $ for selecting multiple list elements. According to ?Extract

The most important distinction between [, [[ and $ is that the [ can select more than one element whereas the other two select a single element.

list_flights[delete_vector] <- NULL

Upvotes: 3

Related Questions