mapvin vin
mapvin vin

Reputation: 81

Get values in list equal to specific conditions

Is there a way to get values from list that is equal to specific values. Example

asd <- list(colb = structure(list(CNT = 1:3), class = "data.frame", row.names = c(NA,3L)), cola = structure(list(CNT = 1L), class = "data.frame", row.names = 1L), colc = structure(list(CNT = 2L), class = "data.frame", row.names = 2L))

Here I need to get only cola since it has 1 row and the value is equal to 1. So basically the condition is the element value should be equal to 1 and has only 1 row

Upvotes: 2

Views: 47

Answers (4)

akrun
akrun

Reputation: 886948

Using keep

library(purrr)
 keep(asd, ~ nrow(.x) == 1&&  1 %in% .x$CNT)
$cola
  CNT
1   1

Upvotes: 0

Darren Tsai
Darren Tsai

Reputation: 35554

A trick with all.equal(..., check.attributes = FALSE):

Filter(\(x) all.equal(x, 1, check.attributes = FALSE), asd)

# $cola
#   CNT
# 1   1

Upvotes: 0

B. Christian Kamgang
B. Christian Kamgang

Reputation: 6489

One way to solve your problem:

Filter(function(x) nrow(x)==1 && all(x==1), asd)

$cola
  CNT
1   1

Upvotes: 1

Sotos
Sotos

Reputation: 51582

You can use Filter on your conditions, i.e.

Filter(length, lapply(asd, \(i)which(nrow(i) == 1 & i$CNT == 1)))

#$cola
#[1] 1

Upvotes: 2

Related Questions