我有一个包含30个变量的数据集,这些变量组成了三个不同的比例(每个10个项目)。考虑到一个小规模的例子,我写了一个函数(在你们的帮助下),从中获取相关矩阵......
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))
答案 0 :(得分: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