2017-06-22 64 views
1

我有一個數據集,其中包含30個變量,它們組成三個不同的尺度(每個10個項目)。考慮到小規模的例子,我寫了需要從這個相關矩陣的功能(從你們的幫助)...在R中,找到每個子測試的相關矩陣

C1 C2 A1 A2 N1 N2 
C1 1 .36 .64 .47 .36 .43 
C2 .36 1 .27 .43 .40 .47 
A1 .64 .27 1 .50 .49 .33 
A2 .47 .43 .50 1 .47 .37 
N1 .36 .40 .49 .47 1 .41 
N2 .43 .47 .33 .37 .41 1 

...這樣的:

C1 C2 A1 A2 N1 N2 
C1 1 .36 0 0 0 0 
C2 .36 1 0 0 0 0 
A1 0 0 1 .50 0 0 
A2 0 0 .50 1 0 0 
N1 0 0 0 0 1 .41 
N2 0 0 0 0 .41 1 

我的目標現在是將這個相關矩陣(基於三個不同尺度中的每一個)存儲到包含三個矩陣的列表中。最終的輸出應該如下所示:

'1' 
    C1 C2 
C1 1 .36 
C2 .36 1 

'2' 
    A1 A2 
A1 1 .50 
A2 .50 1 

'3' 
    N1 N2 
N1 1 .41 
N2 .41 1 

我想象着運行for循環並將結果存儲在列表中將是最好的。可悲的是,我在哪裏開始空白。然而,重要的是,生成上述結果的代碼可以推廣用於包含兩個,三個(如本例),四個或更多子尺度的數據集。

我有一些額外的信息要添加。以下是用於用0代替矩陣中的值的函數。不是變量的參數如下:

num.vars <- 6; num.subscales <- 3; cor.d <- is the table from above 

# Find correlation matrix of each sub-test 
temp <- seq(1, num.vars, 1) 
temp.factors <- split(temp, cut(temp, num.subscales, labels=FALSE)) 
temp.names <- names(d) 

temp.factors <- lapply(temp.factors, function(x) temp.names[x]) 

facReplace <- function(m, f) { 
    x <- do.call("c", f) 
    m1 <- data.frame(m) 
    row.names(m1) <- x 
    names(m1) <- x 
    for (i in 1:length(f)) { 
    for (j in 1:length(x)) { 
     for (k in 1:length(x)) { 
     tempfac <- do.call("c", f[i]) 
     temprow <- x[j] 
     tempcol <- x[k] 
     if (!(temprow %in% tempfac) & (tempcol %in% tempfac)) (m1[j, k] <- 0) 
     } 
    } 
    } 
    return(m1) 
} 
sub.cor.matrix <- as.matrix(facReplace(cor.d, temp.factors)) 

回答

2

你想要做這個嗎?

scales_name通過刪除尾隨數字來獲取唯一的比例屬性。你可以只子集和過濾df得到您的data.frame

> df <- read.table(text = " C1 C2 A1 A2 N1 N2 
+ C1 1 .36 .64 .47 .36 .43 
+   C2 .36 1 .27 .43 .40 .47 
+   A1 .64 .27 1 .50 .49 .33 
+   A2 .47 .43 .50 1 .47 .37 
+   N1 .36 .40 .49 .47 1 .41 
+   N2 .43 .47 .33 .37 .41 1", header = TRUE, row.names = 1) 
> 
> scales_name <- unique(gsub("[:0-9:]", "", colnames(df))) 
> 
> list_cor_mat <- list() 
> for (scale_tmp in scales_name) { 
+ list_cor_mat <- c(list_cor_mat, 
+  list(df[grepl(scale_tmp,rownames(df)), grepl(scale_tmp,colnames(df))]) 
+ ) 
+ } 
> 
> names(list_cor_mat) <- scales_name 
> list_cor_mat 
$C 
    C1 C2 
C1 1.00 0.36 
C2 0.36 1.00 

$A 
    A1 A2 
A1 1.0 0.5 
A2 0.5 1.0 

$N 
    N1 N2 
N1 1.00 0.41 
N2 0.41 1.00 
+0

列表這是一個完美的解決方案。謝謝你,raymkchow! – Josh