如何将R数据框的列转换为单个向量?


有时数据框中的所有列都具有相似的數據特征,代表一个特定的变量。例如,有一个数据框包含五列,每列都是人们的身高。要将此类型的数据框转换为向量,我们可以使用as.vector函数以及as.matrix函数。as.matrix将读取数据框列,以便可以创建值数组。

示例1

 在线演示

考虑以下数据框:

set.seed(101)
x1<−rnorm(20)
x2<−rnorm(20)
x3<−rnorm(20,5,0.34)
df1<−data.frame(x1,x2,x3)
df1

输出

x1 x2 x3
1 −0.3260365 −0.1637557 5.164036
2 0.5524619 0.7085221 5.257793
3 −0.6749438 −0.2679805 4.211429
4 0.2143595 −1.4639218 4.843768
5 0.3107692 0.7444358 4.624170
6 1.1739663 −1.4103902 5.136996
7 0.6187899 0.4670676 5.193438
8 −0.1127343 −0.1193201 4.759932
9 0.9170283 0.4672390 4.901369
10 −0.2232594 0.4981356 4.495481
11 0.5264481 0.8949372 4.608913
12 −0.7948444 0.2791520 4.906680
13 1.4277555 1.0078658 5.196486
14 −1.4668197 −2.0731065 4.525053
15 −0.2366834 1.1898534 5.254680
16 −0.1933380 −0.7243742 4.642597
17 −0.8497547 0.1679838 5.056229
18 0.0584655 0.9203352 5.384135
19 −0.8176704 −1.6716048 5.399066
20 −2.0503078 0.4484691 4.854527

将df1转换为向量:

示例

df1_vector<−as.vector(as.matrix(df1[,c("x1","x2","x3")]))
df1_vector

输出

[1] −0.3260365 0.5524619 −0.6749438 0.2143595 0.3107692 1.1739663
[7] 0.6187899 −0.1127343 0.9170283 −0.2232594 0.5264481 −0.7948444
[13] 1.4277555 −1.4668197 −0.2366834 −0.1933380 −0.8497547 0.0584655
[19] −0.8176704 −2.0503078 −0.1637557 0.7085221 −0.2679805 −1.4639218
[25] 0.7444358 −1.4103902 0.4670676 −0.1193201 0.4672390 0.4981356
[31] 0.8949372 0.2791520 1.0078658 −2.0731065 1.1898534 −0.7243742
[37] 0.1679838 0.9203352 −1.6716048 0.4484691 5.1640360 5.2577927
[43] 4.2114287 4.8437684 4.6241696 5.1369956 5.1934379 4.7599317
[49] 4.9013692 4.4954815 4.6089132 4.9066798 5.1964863 4.5250531
[55] 5.2546796 4.6425965 5.0562295 5.3841351 5.3990656 4.8545265

示例2

 在线演示

y1<−sample(LETTERS[1:26],20)
y2<−sample(LETTERS[1:26],20)
y3<−sample(LETTERS[1:26],20)
y4<−sample(LETTERS[1:26],20)
df2<−data.frame(y1,y2,y3,y4)
df2

输出

  y1 y2 y3 y4
1  G V P Y
2  A J N A
3  E L X L
4  K E B O
5  P Z O E
6  W T T Z
7  X N J U
8  L D L J
9  U U Z X
10 Y B A F
11 F M W I
12 Q P F B
13 T Y H M
14 H C K T
15 I F Y W
16 N G G H
17 R A M K
18 S K E G
19 C O U Q
20 O W D V

将df2转换为向量:

示例

df2_vector<−as.vector(as.matrix(df2[,c("y1","y2","y3","y4")]))
df2_vector

输出

[1] "G" "A" "E" "K" "P" "W" "X" "L" "U" "Y" "F" "Q" "T" "H" "I" "N" "R" "S" "C"
[20] "O" "V" "J" "L" "E" "Z" "T" "N" "D" "U" "B" "M" "P" "Y" "C" "F" "G" "A" "K"
[39] "O" "W" "P" "N" "X" "B" "O" "T" "J" "L" "Z" "A" "W" "F" "H" "K" "Y" "G" "M"
[58] "E" "U" "D" "Y" "A" "L" "O" "E" "Z" "U" "J" "X" "F" "I" "B" "M" "T" "W" "H"
[77] "K" "G" "Q" "V"

更新于:2021年2月8日

1K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告