How to change the first value for each group in data.table object in R?

R ProgrammingServer Side ProgrammingProgramming

To change the first value for each group in data.table object, we can use single square brackets for accessing and changing the value to desired value. For example, if we have a data.table object called DT that contains a group column defined by Class and a numerical column defined by Response then the first value of Response for each Class can be set to say 5 by using the command DT[,Response:=c(2,Response[-]),by=Class]

Consider the below data.table object −

Example

library(data.table)
Group<-sample(c("A","B","C"),20,replace=TRUE)
DT1<-data.table(Group,y)
DT1

Output

   Group y
1:  B   5
2:  A   7
3:  A   4
4:  B   3
5:  B   5
6:  C   7
7:  C   5
8:  A   4
9:  C   6
10: A   5
11: B   6
12: C   5
13: A   9
14: A   4
15: B   5
16: C   3
17: C   3
18: B   8
19: A   7
20: C   2

Changing first value of y for each Group in DT1 to 2 −

Example

DT1[,y:=c(2,y[-1]),by=Group]
DT1

Output

   Group y
1:  B    2
2:  A    2
3:  A    4
4:  B    3
5:  B    5
6:  C    2
7:  C    5
8:  A    4
9:  C    6
10: A    5
11: B    6
12: C    5
13: A    9
14: A    4
15: B    5
16: C    3
17: C    3
18: B    8
19: A    7
20: C    2

Example

Class<-sample(c("First","Second","Third","Fourth"),20,replace=TRUE)
x<-rpois(20,1)
DT2<-data.table(Class,x)
DT2

Output

    Class   x
1: Fourth   1
2: Second   2
3: Second   0
4: Third    0
5: Second   0
6: First    1
7: Third    2
8: First    1
9: Third    0
10: Fourth  3
11: Fourth  0
12: Second  0
13: Third   2
14: Fourth  3
15: Fourth  0
16: Fourth  3
17: Second  0
18: Fourth  1
19: First   0
20: Second  2

Changing first value of x for each Class in DT2 to 3 −

Example

DT2[,x:=c(3,x[-1]),by=Class]
DT2

Output

     Class    x
1:  Fourth    3
2:  Second    3
3:  Second    0
4:  Third     3
5:  Second    0
6:  First     3
7:  Third     2
8:  First     1
9:  Third     0
10: Fourth    3
11: Fourth    0
12: Second    0
13: Third     2
14: Fourth    3
15: Fourth    0
16: Fourth    3
17: Second    0
18: Fourth    1
19: First     0
20: Second    2
raja
Published on 08-Feb-2021 06:28:14
Advertisements