如何更改R中data.table对象中每个组的第一个值?

要更改data.table对象中每个组的第一个值,我们可以使用单个方括号来访问该值并将其更改为所需值。例如,如果我们有一个data.table名为DT的对象,其中包含一个由Class定义的组列和一个由Response定义的数字列,则可以使用命令DT [,Response:= c(2,Response [-]),by = Class]

考虑以下data.table对象-

示例

library(data.table)
Group<-sample(c("A","B","C"),20,replace=TRUE)
DT1<-data.table(Group,y)
DT1
输出结果
   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

将DT1中每个组的y的第一值更改为2-

示例

DT1[,y:=c(2,y[-1]),by=Group]
DT1
输出结果
   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

示例

Class<-sample(c("First","Second","Third","Fourth"),20,replace=TRUE)
x<-rpois(20,1)
DT2<-data.table(Class,x)
DT2
输出结果
    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

将DT2中每个类的x的第一个值更改为3-

示例

DT2[,x:=c(3,x[-1]),by=Class]
DT2
输出结果
     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