如何在不使用列名的情况下将 R 数据框中的多列合并为一列?

要在不使用列名的情况下将 R 数据框中的多列合并为一列,我们可以按照以下步骤操作 -

  • 首先,创建一个数据框。

  • 然后,将数据框转换为单列数据框。

  • 同样,使用row.names函数将数据框转换为单列,行中不显示列名。

创建数据框

让我们创建一个数据框,如下所示 -

例子

x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
df

执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-

输出

  x  y z  a  b  c
1 48 6 8 48 49 22
2 7 34 48 28 17 17
3 25 40 1 22 12 29
4 38 21 27 33 8 5
5 5 20 7 50 46 32

将数据框转换为单列数据框

使用 unlist 函数将 df 转换为单个数据框 -

例子

x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
data.frame(unlist(df))

输出

unlist.df.
x1 48
x2 7
x3 25
x4 38
x5 5
y1 6
y2 34
y3 40
y4 21
y5 20
z1 8
z2 48
z3 1
z4 27
z5 7
a1 48
a2 28
a3 22
a4 33
a5 50
b1 49
b2 17
b3 12
b4 8
b5 46
c1 22
c2 17
c3 29
c4 5
c5 32

将数据框转换为没有列名的单列数据框

使用 unlist 函数将 df 转换为没有由列名表示的行号的单个数据框 -

例子

x<-sample(1:50,5)
y<-sample(1:50,5)
z<-sample(1:50,5)
a<-sample(1:50,5)
b<-sample(1:50,5)
c<-sample(1:50,5)
df<-data.frame(x,y,z,a,b,c)
data.frame(One=unlist(df,use.names=FALSE))

输出

 One
1 48
2 7
3 25
4 38
5 5
6 6
7 34
8 40
9 21
10 20
11 8
12 48
13 1
14 27
15 7
16 48
17 28
18 22
19 33
20 50
21 49
22 17
23 12
24 8
25 46
26 22
27 17
28 29
29 5
30 32

猜你喜欢