将2D矩阵转换为3D矩阵

时间:2019-06-14 13:19:24

标签: r

模拟后,我得到了这样的数据:

/var/log/kube-scheduler.log

,长度为40000行。

但是[1:6,]表示月份,[,1:1:x]表示地区。因此,我想在[1:6]行中有[,1:x]列(在我的数据集28中),并在第三维中具有长度(40000),因为这是模拟。

随后用我的6行28列的3D表,我想做一些简单的操作,例如第1行/第1列的3D值的直方图等...

edit:“ capt2 [3,1]”只是字符列的名称

1 个答案:

答案 0 :(得分:1)

只需将其转换为array

我将模拟一些数据以向您展示如何执行此操作。

set.seed(42)
n <- 10  # `n` in your data would be 40,000
# your rownames
v <- c("capt2[1,1]", "capt2[2,1]", "capt2[3,1]", "capt2[4,1]", "capt2[5,1]", "capt2[6,1]", 
       "capt2[1,2]", "capt2[2,2]", "capt2[3,2]", "capt2[4,2]", "capt2[5,2]", "capt2[6,2]", 
       "capt2[1,3]", "capt2[2,3]", "capt2[3,3]", "capt2[4,3]", "capt2[5,3]", "capt2[6,3]")
M <- matrix(rnorm(3*6*n), n, dimnames=list(NULL, v))  # shall symbolize your data

M[1:2, 1:6]
#      capt2[1,1] capt2[2,1] capt2[3,1]  capt2[4,1]  capt2[5,1] capt2[6,1]
# [1,]  -0.132088  0.5156677  1.3487070  1.01687283 -0.73844075  0.8131950
# [2,]   1.476787 -0.2343653 -0.0227647 -0.02671746  0.04656394 -0.1908165

现在使用正确的array镜片和dim来应用dimnames

A <- array(as.vector(t(M)), dim=c(6, 3, n), 
           dimnames=list(paste0("month.", 1:6), paste0("territory.", 1:3), NULL))
A
# , , 1
# 
#         territory.1 territory.2 territory.3
# month.1  -0.1320880   0.4703934  -1.3870266
# month.2   0.5156677   2.4595935   1.1573471
# month.3   1.3487070  -0.1662615  -0.2901453
# month.4   1.0168728   0.4823695   1.8922020
# month.5  -0.7384408  -0.7848878  -0.2764311
# month.6   0.8131950   1.1454705  -0.3047780
# 
# , , 2
# 
#         territory.1 territory.2 territory.3
# month.1  1.47678742 -1.24267027  -1.3066759
# month.2 -0.23436528 -0.81838032  -1.6824809
# month.3 -0.02276470  0.86256338   0.8285461
# month.4 -0.02671746  0.99294364  -1.3859983
# month.5  0.04656394  0.16341632  -1.1094188
# month.6 -0.19081647  0.03157319   0.5978327
# 
# , , 3
# 
#         territory.1 territory.2 territory.3
# month.1  -0.2170302  1.38157546 -0.76839533
# month.2  -0.6585034 -2.11320011  0.08731909
# month.3   0.2442259  0.09734049 -0.29122771
# month.4   0.7036078 -1.24639550 -0.41482430
# month.5  -1.0175961 -1.23671424  0.13386932
# month.6  -2.6999298 -0.83520581  1.39742941
[...]