How to replace a particular value in R data frame with a new value?

R ProgrammingServer Side ProgrammingProgramming

To replace a particular value in R data frame with a new value, we can use ifelse function where the new value will be placed after the condition and if the column values do not match the condition then the same column will be placed. For example, if we have a data frame called df that contains a column x having 20 values and some of them are 5 and if we want to replace 5 with 2 then we can use the command df$x<-ifelse(df$x==5,2,df$x)

Example

Consider the below data frame −

 Live Demo

ID<-1:20
x<-rpois(20,2)
df1<-data.frame(ID,x)
df1

Output

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

Replacing value 2 in column x with 3 −

Example

df1$x<-ifelse(df1$x==2,3,df1$x)
df1

Output

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

Example

 Live Demo

S.No<-1:20
y<-rpois(20,5)
df2<-data.frame(S.No,y)
df2

Output

   S.No y
1  1   4
2  2   5
3  3   5
4  4   7
5  5   9
6  6   6
7  7   2
8  8   3
9  9   1
10 10  4
11 11  9
12 12  3
13 13  3
14 14  6
15 15  8
16 16  6
17 17  4
18 18  5
19 19  8
20 20  3

Replacing value 4 in column y with 0 −

Example

df2$y<-ifelse(df2$y==4,0,df2$y)
df2

Output

   S.No y
1  1   0
2  2   5
3  3   5
4  4   7
5  5   9
6  6   6
7  7   2
8  8   3
9  9   1
10 10  0
11 11  9
12 12  3
13 13  3
14 14  6
15 15  8
16 16  6
17 17  0
18 18  5
19 19  8
20 20  3
raja
Published on 17-Mar-2021 07:41:37
Advertisements