我的嵌套列表如下所示:
myList <- list(structure(list(id = 1:3, value = c(22, 33, 44),
code = c("943", "943", "3a0"),
product = c("Product 1", "Product 1", "Product 1")),
row.names = c(NA,-3L),
class = c("data.table", "data.frame")),
structure(list(id = 1:3, value = c(22, 33, 44),
code = c("943", "94f", "3a0"),
product = c("Product 2", "Product 2", "Product 2")),
row.names = c(NA,-3L),
class = c("data.table", "data.frame")),
structure(list(id = 1:3, value = c(22, 33, 44),
code = c("977", "943", "3a0"),
product = c("Product 3", "Product 3", "Product 3")),
row.names = c(NA,-3L),
class = c("data.table", "data.frame")))我想删除所有具有多个列表元素的列表对象,这些列表元素具有相同的code。例如,第一个对象[[1]]有两个条目,其代码为943。我想删除整个对象,只保留那些没有任何副本的对象。
The expected outcome would therefore be: myList <- list(
structure(list(id = 1:3, value = c(22, 33, 44),
code = c("943", "94f", "3a0"),
product = c("Product 2", "Product 2", "Product 2")),
row.names = c(NA,-3L),
class = c("data.table", "data.frame")),
structure(list(id = 1:3, value = c(22, 33, 44),
code = c("977", "943", "3a0"),
product = c("Product 3", "Product 3", "Product 3")),
row.names = c(NA,-3L),
class = c("data.table", "data.frame")))我在考虑使用和lapply,但是我不能把它用到qwork上。
any(duplicated(myList[[1]]$code))有什么想法或建议吗?
这看起来是一个相对简单的问题,但我想不出来
发布于 2021-05-11 21:28:46
这样做是可行的:
myList[sapply(lapply(myList, function(x) +duplicated(x$code)), function(x) sum(x) == 0)]
[[1]]
id value code product
1: 1 22 943 Product 2
2: 2 33 94f Product 2
3: 3 44 3a0 Product 2
[[2]]
id value code product
1: 1 22 977 Product 3
2: 2 33 943 Product 3
3: 3 44 3a0 Product 3发布于 2021-05-11 21:51:49
您的代码any(duplicated(myList[[1]]$code))可以在Filter中使用
Filter(function(x) !any(duplicated(x$code)), myList)
#[[1]]
# id value code product
#1: 1 22 943 Product 2
#2: 2 33 94f Product 2
#3: 3 44 3a0 Product 2
#[[2]]
# id value code product
#1: 1 22 977 Product 3
#2: 2 33 943 Product 3
#3: 3 44 3a0 Product 3或者使用purrr:
purrr::keep(myList, ~!any(duplicated(.x$code)))
purrr::discard(myList, ~any(duplicated(.x$code)))https://stackoverflow.com/questions/67487584
复制相似问题