如何在R中合并data.table对象的两列?
data.table对象与数据帧几乎相同。要合并data.table对象的两列,我们可以使用paste0函数。例如,如果我们有一个定义为DT的数据框,其中包含名为x和y的两列,则可以使用以下命令将它们组合。
DT[,xy:=paste0(x,y)]
示例
加载data.table包。
> library(data.table)
考虑下面的data.table对象。
示例
> x<-1:20> y<-letters[1:20]
> dt1<-data.table(x,y)
> dt1
输出结果
x y1: 1 a
2: 2 b
3: 3 c
4: 4 d
5: 5 e
6: 6 f
7: 7 g
8: 8 h
9: 9 i
10: 10 j
11: 11 k
12: 12 l
13: 13 m
14: 14 n
15: 15 o
16: 16 p
17: 17 q
18: 18 r
19: 19 s
20: 20 t
组合列x和y。
示例
> dt1[,xy:=paste0(x,y)]> dt1
输出结果
x y xy1: 1 a 1a
2: 2 b 2b
3: 3 c 3c
4: 4 d 4d
5: 5 e 5e
6: 6 f 6f
7: 7 g 7g
8: 8 h 8h
9: 9 i 9i
10: 10 j 10j
11: 11 k 11k
12: 12 l 12l
13: 13 m 13m
14: 14 n 14n
15: 15 o 15o
16: 16 p 16p
17: 17 q 17q
18: 18 r 18r
19: 19 s 19s
20: 20 t 20t
让我们看另一个例子。
示例
> Group<-sample(c("G1","G2","G3","G4"),20,replace=TRUE)> Class<-sample(c("I","II","III"),20,replace=TRUE)
> dt2<-data.table(Group,Class)
> dt2
输出结果
Group Class1: G3 I
2: G1 II
3: G3 II
4: G4 I
5: G1 I
6: G3 II
7: G1 III
8: G3 I
9: G2 III
10: G3 II
11: G3 I
12: G2 II
13: G2 II
14: G3 III
15: G4 III
16: G4 I
17: G2 II
18: G4 II
19: G1 III
20: G4 II
组合列组和类。
示例
> dt2[,GC:=paste0(Group,Class)]> dt2
输出结果
Group Class GC1: G3 I G3I
2: G1 II G1II
3: G3 II G3II
4: G4 I G4I
5: G1 I G1I
6: G3 II G3II
7: G1 III G1III
8: G3 I G3I
9: G2 III G2III
10: G3 II G3II
11: G3 I G3I
12: G2 II G2II
13: G2 II G2II
14: G3 III G3III
15: G4 III G4III
16: G4 I G4I
17: G2 II G2II
18: G4 II G4II
19: G1 III G1III
20: G4 II G4II
以上是 如何在R中合并data.table对象的两列? 的全部内容, 来源链接: utcz.com/z/343282.html