2016-12-01 261 views
3

我有一個數組,其中包括兩個熟練變量(theta0,theta1)在一個項目上(是,否),稱爲「comp」。這需要轉換爲一個矩陣。有什麼方法可以將底部的矩陣轉換成矩陣嗎?將數組轉換爲矩陣R

我的數組是這樣的:

>priCPT.i6 

, , comp = Yes 

theta1 
theta0  Low  Med  High 
    Low 0.8377206 0.6760511 0.4576021 
    Med 0.6760511 0.4576021 0.2543239 
    High 0.4576021 0.2543239 0.1211734 

, , comp = No 

    theta1 
theta0  Low  Med  High 
    Low 0.1622794 0.3239489 0.5423979 
    Med 0.3239489 0.5423979 0.7456761 
    High 0.5423979 0.7456761 0.8788266 

attr(,"class") 
[1] "CPA" "array" 

我很抱歉,我不能生產的東西,你可以玩。我在尋找的東西,如:

theta0 theta1 Yes  No 
Low  Low  0.8377206 0.1622794 
Low  Med  ..   .. 
Low  High  ..   .. 
Med  Low  ..   .. 
Med  Med  ..   .. 
Med  High  ..   .. 
High  Low  ..   .. 
High  Med  ..   .. 
High  High  ..   .. 

問候......

+0

'tidyr :: s pread(as.data.frame.table(priCPT.i6),Var3,Freq)' – alistaire

回答

6

您可以輕鬆地在第三保證金扁平化矩陣獲取值的列:

z1 <- apply(priCPT.i6, 3L, c) 
## we can also simply use `matrix`; but remember to set `dimnames` 
## otherwise we lose dimnames 
## z1 <- matrix(priCPT.i6, ncol = 2L, 
##    dimnames = list(NULL, dimnames(priCPT.i6)[[3]])) 

你需要的是什麼剩下的就是追加「dimnames」列:

z2 <- expand.grid(dimnames(priCPT.i6)[1:2]) 

現在你可以將它們合併成一個數據幀(你defin itely需要比基體中的數據幀,因爲z1列通過是數字而z2列字符):使用reshape2將

data.frame(z2, z1) 

重現的實例

x <- array(1:18, dim = c(3L, 3L, 2L), dimnames = list(
      c("Low", "Medium", "High"), c("Low", "Medium", "High"), c("Yes", "No"))) 

#, , Yes 
# 
#  Low Medium High 
#Low  1  4 7 
#Medium 2  5 8 
#High  3  6 9 
# 
#, , No 
# 
#  Low Medium High 
#Low  10  13 16 
#Medium 11  14 17 
#High 12  15 18 

z1 <- apply(x, 3L, c) 
## z1 <- matrix(x, ncol = 2L, dimnames = list(NULL, dimnames(x)[[3]])) 
z2 <- expand.grid(dimnames(x)[1:2]) 
data.frame(z2, z1) 

# Var1 Var2 Yes No 
#1 Low Low 1 10 
#2 Medium Low 2 11 
#3 High Low 3 12 
#4 Low Medium 4 13 
#5 Medium Medium 5 14 
#6 High Medium 6 15 
#7 Low High 7 16 
#8 Medium High 8 17 
#9 High High 9 18 
+1

感謝您的快速準確回覆。這完全回答了我的問題。我真的很感激。祝你有美好的一天。! – amisos55

+0

啊我明白了。我最初想到使用'as.data.frame.table(x)':但我看不到一個合適的方法,只有'dcast(as.data.frame.table(x),Var1 + Var2〜Var3, value.var =「Freq」)'不會很快 – user20650

+0

'ftable(x)'如果返回了一些有用的東西,將會是最好的。或'dd < - data.frame(as.table(x)); reshape(dd,dir ='w',idvar = names(dd)[1:2],timevar = names(dd)[3]) – rawr

3

一種替代be

x <- array(1:18, dim = c(3L, 3L, 2L), dimnames = list(
      c("Low", "Medium", "High"), 
      c("Low", "Medium", "High"), 
      c("Yes", "No"))) 

library(reshape2) 
df <- dcast(melt(x), Var1+Var2~Var3) 
df 

    Var1 Var2 Yes No 
1 Low Low 1 10 
2 Low Medium 4 13 
3 Low High 7 16 
4 Medium Low 2 11 
5 Medium Medium 5 14 
6 Medium High 8 17 
7 High Low 3 12 
8 High Medium 6 15 
9 High High 9 18 
+0

感謝您的幫助。 – amisos55