根据列值在列表中删除数据框

时间:2020-05-06 20:39:16

标签: r

我有以下列表:

/* Note That 1000 is equivalent of 1 seconds */

setTimeout(function(){ 
    document.getElementById("demo").innerHTML = "Updated Just Now";
}, 30000); /* This value is equivalent of 30 seconds */

setTimeout(function(){ 
    document.getElementById("demo").innerHTML = "Updated Moments Ago";
}, 300000); /* This value is equivalent of 5 minutes */

我的目标是根据df1 <- data.frame(a = rnorm(20), b = 010037) df2 <- data.frame(a = rnorm(20), b = 010038) df3 <- data.frame(a = rnorm(20), b = 010039) df4 <- data.frame(a = rnorm(20), b = 010040) ls <- list(df1, df2, df3, df4) 列中的值删除选定的数据帧。

b

因此,unwanted <- c(010037, 010038) sapply(ls, "[", "b") %in% unwanted df1将从df2中删除,但我对此并不走运。请帮忙吗?

2 个答案:

答案 0 :(得分:1)

一种选择是先subset然后再Filter

out <- Filter(nrow, lapply(ls, subset, subset = !b %in% unwanted))
length(out)
#[1] 2

或与discard

library(purrr)
map_lgl(ls, ~ all(.x$b %in% unwanted)) %>% 
     discard(ls, .)

或者使用bind_rowsgroup_split

library(dplyr)
bind_rows(ls) %>% 
   filter(!b %in% unwanted) %>% 
   group_split(b)

答案 1 :(得分:1)

这是解决问题的另一种方法:

ls[sapply(ls, function(X) !any(X[["b"]] %in% unwanted))]