How to update single value in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To update single value in an R data frame, we can use row and column indices with single square brackets.

For example, if we have a data frame called df that contains two columns and ten rows and if we want to change the fifth value in second column to 10 then we can use the command given below −

df[5,2]<-10

Check out the below examples to understand how it can be done.

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  0
2  3  1  1
3  2  1  1
4  1  1  0
5  1  3  1
6  3  0  3
7  1  1  1
8  0  1  0
9  0  0  0
10 0  2  0
11 1  1  0
12 2  0  0
13 2  1  2
14 2  0  2
15 0  0  2
16 1  1  2
17 3  1  0
18 0  0  3
19 0  1  0
20 2  1  1

To change 10th value in column 3 to 3, 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[10,3]<-3
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  0
2  3  1  1
3  2  1  1
4  1  1  0
5  1  3  1
6  3  0  3
7  1  1  1
8  0  1  0
9  0  0  0
10 0  2  3
11 1  1  0
12 2  0  0
13 2  1  2
14 2  0  2
15 0  0  2
16 1  1  2
17 3  1  0
18 0  0  3
19 0  1  0
20 2  1  1

Example 2

Following snippet creates a sample data frame −

y1<-sample(1:9,20,replace=TRUE)
y2<-sample(1:9,20,replace=TRUE)
y3<-sample(1:9,20,replace=TRUE)
df2<-data.frame(y1,y2,y3)
df2

The following dataframe is created −

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

To change 12th value in column 1 to 5, add the following code to the above snippet −

y1<-sample(1:9,20,replace=TRUE)
y2<-sample(1:9,20,replace=TRUE)
y3<-sample(1:9,20,replace=TRUE)
df2<-data.frame(y1,y2,y3)
df2[12,1]<-5
df2

Output

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

   y1 y2 y3
1  9  1  6
2  5  8  8
3  7  3  7
4  8  1  6
5  9  6  7
6  5  1  1
7  5  8  2
8  7  2  5
9  7  4  6
10 5  4  4
11 4  8  7
12 5  1  8
13 5  2  9
14 1  8  3
15 2  6  5
16 5  1  6
17 2  5  3
18 8  5  4
19 9  2  2
20 4  5  9
raja
Published on 22-Nov-2021 07:04:37

Advertisements