2011-03-09 32 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