Home > Net >  Remove values from one list based on the IDs removed from another
Remove values from one list based on the IDs removed from another

Time:04-08

I have a data frame that I have split into a list based on ID (l1). I also have another list l2 that is connected to l1 based on the ID names. One of the list elements has a NA value, and I have removed that element out of the list (l2_new).

I would like to be able to remove the same ID value from l1 that I removed from l2 due to the NA value leading to the expected object. Is there a good way to do this (preferably in base R)?

library(lubridate)
library(tidyverse)

date <- rep_len(seq(dmy("01-01-2013"), dmy("31-12-2013"), by = "days"), 300)
ID <-  rep(c("A","B","C"), 50)
df <- data.frame(date = date,
                   utm_x = runif(length(date), min = 238785, max = 453354.5),
                   utm_y = runif(length(date), min = 4096853.0  , max = 4280487.1 ),
                   ID)

l1 <- df %>% 
  group_split(ID)

names(l1) <- sapply(l1, function(x) paste(x$ID[1],
                                            sep = '_'))

l2 <- list(1,2,NA)
names(l2) <- c("A", "B", "C")

l2_new <- Filter(function(a) any(!is.na(a)), l2)

expected <- l2[-3]

CodePudding user response:

We can use the names of 'l2_new' to subset the 'l2'

l2[names(l2_new)]
  • Related