如何通过R中的行创建数据帧值的向量?
要按行创建数据帧值的向量,我们可以在将数据帧与t换位后使用c函数。例如,如果我们有一个包含许多列的数据帧df,则可以使用c(t(df))将df值转换为向量,这将逐行打印数据帧的值。
例1
set.seed(798) x1<−rnorm(20,5,2) x2<−rnorm(20,5,3) df1<−data.frame(x1,x2) df1
输出结果
x1 x2 1 2.786103 −3.098242 2 8.533086 5.943967 3 10.291147 5.841057 4 5.449163 3.989173 5 5.810170 6.463880 6 4.479613 8.594108 7 7.569711 2.420207 8 8.058095 4.875600 9 3.827098 5.239763 10 5.807293 6.416752 11 4.431298 5.827411 12 4.140034 4.705993 13 6.643332 1.450062 14 1.787068 11.405792 15 5.356992 5.258035 16 5.027659 6.665030 17 3.617873 4.955072 18 8.190755 2.514271 19 4.675561 6.849762 20 10.532212 6.050328 Vector_df1<−c(t(df1)) Vector_df1 [1] 2.786103 −3.098242 8.533086 5.943967 10.291147 5.841057 5.449163 [8] 3.989173 5.810170 6.463880 4.479613 8.594108 7.569711 2.420207 [15] 8.058095 4.875600 3.827098 5.239763 5.807293 6.416752 4.431298 [22] 5.827411 4.140034 4.705993 6.643332 1.450062 1.787068 11.405792 [29] 5.356992 5.258035 5.027659 6.665030 3.617873 4.955072 8.190755 [36] 2.514271 4.675561 6.849762 10.532212 6.050328 is.vector(Vector_df1) [1] TRUE
例2
y1<−rpois(20,10) y2<−rpois(20,5) y3<−rpois(20,3) df2<−data.frame(y1,y2,y3) df2
输出结果
y1 y2 y3 1 6 7 1 2 7 7 4 3 16 6 3 4 12 4 4 5 9 4 3 6 10 3 4 7 8 4 1 8 12 4 0 9 9 4 4 10 15 4 5 11 4 6 5 12 10 4 2 13 8 9 2 14 7 4 5 15 9 7 3 16 8 3 7 17 9 6 3 18 6 3 3 19 11 6 7 20 7 2 0 Vector_df2<−c(t(df2)) Vector_df2 [1] 6 7 1 7 7 4 16 6 3 12 4 4 9 4 3 10 3 4 8 4 1 12 4 0 9 [26] 4 4 15 4 5 4 6 5 10 4 2 8 9 2 7 4 5 9 7 3 8 3 7 9 6 [51] 3 6 3 3 11 6 7 7 2 0 is.vector(Vector_df2) [1] TRUE
例子3
z1<−letters[1:20] z2<−rexp(20,1.98) z3<−runif(20,1,5) df3<−data.frame(z1,z2,z3) df3
输出结果
z1 z2 z3 1 a 0.30649942 2.581508 2 b 0.49573688 1.005800 3 c 0.32632915 1.582261 4 d 0.16866850 2.364847 5 e 0.49920925 4.822604 6 f 0.48753521 2.516127 7 g 1.11453076 1.369764 8 h 0.03852521 3.055764 9 i 0.43320666 4.336745 10 j 1.53110506 1.253256 11 k 1.02885841 3.401008 12 l 0.93749136 1.272466 13 m 0.05544727 1.839311 14 n 0.06982751 3.857567 15 o 0.03554147 2.816643 16 p 0.27870340 4.920266 17 q 0.30576924 1.781030 18 r 0.13628651 2.365232 19 s 1.23068290 4.879601 20 t 0.31617628 1.026273 Vector_df3<−c(t(df3)) Vector_df3 [1] "a" "0.30649942" "2.581508" "b" "0.49573688" [6] "1.005800" "c" "0.32632915" "1.582261" "d" [11] "0.16866850" "2.364847" "e" "0.49920925" "4.822604" [16] "f" "0.48753521" "2.516127" "g" "1.11453076" [21] "1.369764" "h" "0.03852521" "3.055764" "i" [26] "0.43320666" "4.336745" "j" "1.53110506" "1.253256" [31] "k" "1.02885841" "3.401008" "l" "0.93749136" [36] "1.272466" "m" "0.05544727" "1.839311" "n" [41] "0.06982751" "3.857567" "o" "0.03554147" "2.816643" [46] "p" "0.27870340" "4.920266" "q" "0.30576924" [51] "1.781030" "r" "0.13628651" "2.365232" "s" [56] "1.23068290" "4.879601" "t" "0.31617628" "1.026273" is.vector(Vector_df3) [1] TRUE