2012-03-10 28 views
-4

我需要建立一个依赖矩阵与我的数据集的所有91个变量。依赖矩阵

我试图使用一些代码,但我没有成功。

给你的重要的代码部分:

p<- length(dati) 
chisquare <- matrix(dati, nrow=(p-1), ncol=p) 

应该创建一个方形矩阵,所有变量

system.time({for(i in 1:p){ 
    for(j in 1:p){ 
     a <- dati[, rn[i+1]] 
     b <- dati[, cn[j]] 
     chisquare[i, (1:(p-1))] <- chisq.test(dati[,i], dati[, i+1])$statistic 
     chisquare[i, p] <- chisq.test(dati[,i], dati, i+1])$p.value 
    }} 
}) 

应该涉及的“P”变量来分析它们是否相互依赖

Error in `[.data.frame`(dati, , rn[i + 1]) : 
    not defined columns selected 

Moreover: There are 50 and more alerts (use warnings() to read the first 50) 

Timing stopped at: 32.23 0.11 32.69 

warnings() #let's check 
>: In chisq.test(dati[, i], dati[, i + 1]) : 
    Chi-squared approximation may be incorrect 

chisquare #all the cells(unl在最后一列ESS这似乎有p值)的行具有相同的值

我也试过另一种方式,这是由人谁知道如何管理[R好多比我提供了我:

#strange values I have in some columns 
sum(dati == 'x') 

#replacing "x" by x 
x <- dati[dati=='x'] 

#distribution of answers for each question 
answers <- t(sapply(1:ncol(dati), function(i) table(factor(dati[, i], levels = -2:9), useNA = 'always'))) 

rownames(answers) <- colnames(dati) 
answers 
#correlation for the pairs 

I<- diag(ncol(dati)) 
#empty diagonal matrix 

colnames(I) <- rownames(I) <- colnames(dati) 
rn <- rownames(I) 
cn <- colnames(I) 

#loop 
system.time({ 
    for(i in 1:ncol(dati)){ 
     for(j in 1:ncol(spain)){ 
      a <- dati[, rn[i]] 
      b <- dati[, cn[j]] 
      r <- chisq.test(a,b)$statistic 
      r <- chisq.test(a,b)$p.value 
      I[i, j] <- r 
     } 
    } 
}) 

user system elapsed 
    29.61 0.09 30.70 

There are 50 and more alerts (use warnings() to read the first 50) 

warnings() #let's check 
-> : In chisq.test(a, b) : Chi-squared approximation may be incorrect 

diag(I)<- 1 

#result 
head(I) 

列停在第5个变量,而我需要检查所有变量之间的依赖关系。每一个。

我不明白的地方,我错了,但我希望我不是那么远,

我希望得到一个很好的帮助,请。

+1

你应该研究你的问题的格式... – 2012-03-10 19:17:31

+1

应该尝试使问题标题更具体,并将更具代表性的标签(例如编程语言) – msonsona 2012-03-10 19:21:04

回答

1

您显然正在尝试计算数据集中所有变量对的卡方检验的p值,即 。 这可以按照如下方式完成。

# Sample data 
n <- 1000 
k <- 10 
d <- matrix(sample(LETTERS[1:5], n*k, replace=TRUE), nc=k) 
d <- as.data.frame(d) 
names(d) <- letters[1:k] 

# Compute the p-values 
k <- ncol(d) 
result <- matrix(1, nr=k, nc=k) 
rownames(result) <- colnames(result) <- names(d) 
for(i in 1:k) { 
    for(j in 1:k) { 
     result[i,j] <- chisq.test(d[,i], d[,j])$p.value 
    } 
} 

此外,可能有一些错误数据, 导致你的警告, 但我们不知道这件事。

你的代码有太多的问题,我试图枚举他们 (你开始尝试创建一个不同数字的行和列的数字 ,然后我完全失去了)。