假设我有以下矩阵a(下面的输入):
> a
[,1] [,2] [,3] [,4]
[1,] 26.96318 136.3067 237.9886 399.4045
[2,] 55.36927 182.4738 246.5615 385.9003
[3,] 97.10758 122.8290 285.2592 325.1235
[4,] 80.23753 197.0916 203.1537 328.1359
[5,] 17.92519 109.8690 251.1775 328.4357
[6,] 71.45958 118.3602 249.6157 338.3364
[7,] 16.78765 161.3456 206.6488 385.8919
[8,] 32.80423 105.7197 234.8725 367.6513
[9,] 73.56880 108.8779 215.4797 316.6170
[10,] 41.08425 146.8893 211.2142 338.3543
如何线性化(获取矢量): 1.逐列 2.逐行
例如,逐列结果如下所示:
[1] 26.96318 55.36927 97.10758 80.23753 17.92519 71.45958 16.78765 32.80423 73.56880 41.08425 136.30665 182.47378
[13] 122.82902 197.09157 109.86903 118.36019 161.34561 105.71971 108.87791 146.88933 237.98864 246.56151 285.25918 203.15367
[25] 251.17751 249.61567 206.64882 234.87252 215.47969 211.21424 399.40453 385.90034 325.12346 328.13589 328.43573 338.33636
[37] 385.89189 367.65128 316.61704 338.35429
> dput(a)
structure(c(26.9631815841421, 55.369265563786, 97.1075813053176,
80.237529752776, 17.9251873865724, 71.4595773722976, 16.7876488063484,
32.8042338369414, 73.568799556233, 41.0842498764396, 136.306652054191,
182.473776396364, 122.829020931385, 197.091567260213, 109.869031514972,
118.360190931708, 161.345613677986, 105.719711235724, 108.877905877307,
146.889329864644, 237.988638831303, 246.561505645514, 285.259176045656,
203.153668926097, 251.177511387505, 249.615669064224, 206.648816983216,
234.872522787191, 215.479686786421, 211.214235564694, 399.404528317973,
385.90033929795, 325.123458285816, 328.135887836106, 328.43573493883,
338.336359220557, 385.891888826154, 367.651279014535, 316.617037914693,
338.354286877438), .Dim = c(10L, 4L))
答案 0 :(得分:3)
as.vector()
会将您的矩阵逐列转换为矢量:
> as.vector(a)
[1] 26.96318 55.36927 97.10758 80.23753 17.92519 71.45958 16.78765
[8] 32.80423 73.56880 41.08425 136.30665 182.47378 122.82902 197.09157 ...
要获得逐行结果,请先使用t()
转换它:
> as.vector(t(a))
[1] 26.96318 136.30665 237.98864 399.40453 55.36927 182.47378 246.56151
[8] 385.90034 97.10758 122.82902 285.25918 325.12346 80.23753 197.09157 ...