2011-03-09 174 views
1

我想读取一个csv文件,然后从csv文件的每一行中创建3个矩阵,然后应用使用方法chisq.test的卡方检验(矩阵),但不知何故,这种方法似乎失败了。在R中使用chisq.test(卡方测试)

它给了我下面的错误:

Error in sum(x) : invalid 'type' (list) of argument

在另一方面,如果我只需创建一个矩阵通过一些数字,然后它工作正常。 我也尝试在两种类型的矩阵上运行str。

  1. 我使用csv文件中的行创建。 str on that给出:

    List of 12 
    $ : int 3 
    $ : int 7 
    $ : int 3 
    $ : int 1 
    $ : int 7 
    $ : int 3 
    $ : int 1 
    $ : int 1 
    $ : int 1 
    $ : int 0 
    $ : int 2 
    $ : int 0 
    - attr(*, "dim")= int [1:2] 4 3 
    
  2. 使用某些数字创建的矩阵。对海峡给出:

    num [1:2, 1:3] 1 2 3 4 5 6 
    

有人能告诉我这到底是怎么回事呢?谢谢。

+2

您正在向chisq.test传递一个列表,而不是矩阵。让我们看看你的代码,甚至更好。一个小的可重现的例子。 – 2011-03-09 08:00:17

+2

建议阅读:http://cran.r-project.org/doc/manuals/R-lang.html#Objects – nico 2011-03-09 08:15:09

回答

2

问题是你的数据结构是一个列表数组,而对于chisq.test()你需要一个数值数组。

一个解决方案是使用as.numeric()将数据强制转换为数字。我在下面演示这个。另一个解决方案是在创建数组之前将您的read.csv()的结果转换为数字。

# Recreate data 
x <- structure(array(list(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)), dim=c(3,4)) 
str(x) 

List of 12 
$ : num 1 
$ : num 2 
$ : num 3 
$ : num 4 
$ : num 5 
$ : num 6 
$ : num 7 
$ : num 8 
$ : num 9 
$ : num 10 
$ : num 11 
$ : num 12 
- attr(*, "dim")= int [1:2] 3 4 

# Convert to numeric array 
x <- array(as.numeric(x), dim=dim(x)) 
str(x) 

num [1:3, 1:4] 1 2 3 4 5 6 7 8 9 10 ... 

chisq.test(x) 

    Pearson's Chi-squared test 

data: x 
X-squared = 0.6156, df = 6, p-value = 0.9961 

Warning message: 
In chisq.test(x) : Chi-squared approximation may be incorrect 
+0

谢谢,它完全奏效。 :) – dhaval2025 2011-03-09 18:22:50