How to check if a variable contains number greater than 1 in an R data frame?

The variables in an R data frame are referred to as the columns of the data frame. Sometimes we have a threshold value for a particular column and we need to check whether all the values in that column are greater than or less than the threshold. For this purpose, we can make use of ifelse function as shown in the below examples.

Example1

Live Demo

Consider the below data frame −

set.seed(24)
x<−rnorm(20,1,0.25)
df1<−data.frame(x)
df1

Output

      x
1 0.8635298
2 1.1341463
3 1.1049058
4 0.8540932
5 1.2118650
6 1.0665055
7 1.1111463
8 0.8833762
9 0.7879075
10 1.0005780
11 0.6707730
12 1.1495673
13 0.8094464
14 0.6427274
15 1.0830611
16 0.8827348
17 0.9162533
18 1.3840630
19 1.1524986
20 1.1290839

Checking whether values in column x are greater than 1 or not −

Output

[1] "No" "No" "No" "No" "No" "No" "Yes" "Yes" "Yes" "No" "No" "No"
[13] "No" "Yes" "No" "No" "No" "Yes" "No" "No"

Example3

Live Demo

z<−sample(0:5,20,replace=TRUE)
df3<−data.frame(z)
df3

Output

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

Checking whether values in column z are greater than 1 or not −

Example

ifelse(df3\$z>1,"Yes","No")

Output

[1] "Yes" "Yes" "No" "No" "No" "No" "Yes" "Yes" "Yes" "Yes" "No" "No"
[13] "No" "No" "Yes" "Yes" "Yes" "No" "No" "Yes"

Updated on: 05-Feb-2021

782 Views