Replace all values in an R data frame if they are greater than a certain value.

To replace all values in an R data frame if they are greater than a certain value, we can use apply function with ifelse function.

For Example, if we have a data frame called df and we want to replace all values in df with 5 if they are greater than 10 then we can use the command given below −

df[]<-apply(df,2,function(x) ifelse(x0,1,x))

Example 1

Following snippet creates a sample data frame −

x1<-rpois(20,1)
x2<-rpois(20,1)
x3<-rpois(20,1)
df1<-data.frame(x1,x2,x3)
df1

The following dataframe is created

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

To replace all values in df1 with 1 if they are greater than 0 on the above created data frame, add the following code to the above snippet −

x1<-rpois(20,1)
x2<-rpois(20,1)
x3<-rpois(20,1)
df1<-data.frame(x1,x2,x3)
df1[]<-apply(df1,2,function(x) ifelse(x0,1,x))
df1

Output

If you execute all the above given snippets as a single program, it generates the following Output −

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

Example 2

Following snippet creates a sample data frame −

y1<-round(rnorm(20),1)
y2<-round(rnorm(20),1)
y3<-round(rnorm(20),1)
df2<-data.frame(y1,y2,y3)
df2

The following dataframe is created

     y1   y2   y3
1 -0.9 -0.2 -1.0
2  0.8  0.0  0.0
3 -0.2  0.6 -1.2
4 -0.5  0.5  1.2
5  1.1  1.2  1.2
6 0.2  -1.2  0.4
7 -2.2 -0.4  1.6
8 -0.7  0.0 -0.2
9 -0.4  1.1 -1.7
10  0.0 -1.0  0.6
11  0.1 -1.3 -0.1
12  0.7  0.0 -2.2
13  0.8 -0.1  0.5
14 -1.1 -0.3 -1.2
15 -0.4  1.3 -0.5
16  1.7  0.0 -0.3
17 -0.4 -2.4 -0.9
18 -0.5  2.1  0.6
19  0.2  1.1 -1.7
20 -0.3  0.1 -0.7

To replace all values in df2 with 0.5 if they are greater than 0.1 on the above created data frame, add the following code to the above snippet −

y1<-round(rnorm(20),1)
y2<-round(rnorm(20),1)
y3<-round(rnorm(20),1)
df2<-data.frame(y1,y2,y3)
df2[]<-apply(df2,2,function(x) ifelse(x0.1,0.5,x))
df2

Output

If you execute all the above given snippets as a single program, it generates the following Output −

     y1    y2  y3
1 -0.9 -0.2 -1.0
2  0.5  0.0  0.0
3 -0.2  0.5 -1.2
4 -0.5  0.5  0.5
5  0.5  0.5  0.5
6  0.5 -1.2  0.5
7 -2.2 -0.4  0.5
8 -0.7  0.0 -0.2
9 -0.4  0.5 -1.7
10  0.0 -1.0  0.5
11  0.1 -1.3 -0.1
12  0.5  0.0 -2.2
13  0.5 -0.1  0.5
14 -1.1 -0.3 -1.2
15 -0.4  0.5 -0.5
16  0.5  0.0 -0.3
17 -0.4 -2.4 -0.9
18 -0.5  0.5  0.5
19  0.5  0.5 -1.7
20 -0.3  0.1 -0.7

Updated on: 09-Nov-2021

2K+ Views