How to check if a list element is greater than a certain value in R?


If we have a list that contains numeric elements and we want to check whether the elements are greater than a certain value then as.numeric function can be used. The output of the function will be in 0/1 format where 0 represents FALSE and 1 represents TRUE. For example, if we have a list called LIST then to check whether elements in LIST are greater than 2 can be done as as.numeric(LIST>2).

Example1

 Live Demo

List1<−list(1,2,2,2,4,1,2,5,5,2,3,5,2,2,2,2,5,5,8,9,6,5,5)
List1

Output

[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 2
[[4]]
[1] 2
[[5]]
[1] 4
[[6]]
[1] 1
[[7]]
[1] 2
[[8]]
[1] 5
[[9]]
[1] 5
[[10]]
[1] 2
[[11]]
[1] 3
[[12]]
[1] 5
[[13]]
[1] 2
[[14]]
[1] 2
[[15]]
[1] 2
[[16]]
[1] 2
[[17]]
[1] 5
[[18]]
[1] 5
[[19]]
[1] 8
[[20]]
[1] 9
[[21]]
[1] 6
[[22]]
[1] 5
[[23]]
[1] 5

Checking whether elements in List1 are greater than 5 or not −

Example

as.numeric(List1>5)

Output

[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0

Example2

 Live Demo

List2<−list(4,7,5,4,1,2,5,2,3,6,5,7,7,1,1,2,5,5,9,2)
List2

Example

[[1]]
[1] 4
[[2]]
[1] 7
[[3]]
[1] 5
[[4]]
[1] 4
[[5]]
[1] 1
[[6]]
[1] 2
[[7]]
[1] 5
[[8]]
[1] 2
[[9]]
[1] 3
[[10]]
[1] 6
[[11]]
[1] 5
[[12]]
[1] 7
[[13]]
[1] 7
[[14]]
[1] 1
[[15]]
[1] 1
[[16]]
[1] 2
[[17]]
[1] 5
[[18]]
[1] 5
[[19]]
[1] 9
[[20]]
[1] 2

Checking whether elements in List2 are greater than 2 or not −

Example

as.numeric(List2>2)

Output

[1] 1 1 1 1 0 0 1 0 1 1 1 1 1 0 0 0 1 1 1 0

Updated on: 09-Feb-2021

695 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements