Home > Software design >  Get values in list equal to specific conditions
Get values in list equal to specific conditions

Time:12-29

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

CodePudding user response:

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

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

#$cola
#[1] 1

CodePudding user response:

One way to solve your problem:

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

$cola
  CNT
1   1

CodePudding user response:

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

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

# $cola
#   CNT
# 1   1
  •  Tags:  
  • r
  • Related