?chisq.test
告訴我們:
Arguments:
x: a numeric vector or matrix. ‘x’ and ‘y’ can also both be
factors.
y: a numeric vector; ignored if ‘x’ is a matrix. If ‘x’ is a
factor, ‘y’ should be a factor of the same length.
如果我們看一下df
按你的Q,你定義的子集是:
> is.numeric(df[1,1:3])
[1] FALSE
> is.vector(df[1,1:3])
[1] FALSE
> is.matrix(df[1,1:3])
[1] FALSE
和你的其他相同子集。然後發生在上帝的一圈。什麼在內部發生的是,作爲df[1,1:3]
是一個數據幀,它首先被轉換到一列矩陣,並從那裏到向量:
Browse[2]> x ## here x is df[1,1:3]
[1] 1 2 3
而df[1,4:6]
(y
在chisq.test
函數)保持不變:
Browse[2]> y
X4 X5 X6
1 4 5 6
當代碼調用complete.cases(x,y)
,我們得到的錯誤你彙報:
Browse[2]> complete.cases(x, y)
Error in complete.cases(x, y) : not all arguments have the same length
complete.cases
調用內部代碼,所以我們不能看到發生了什麼,但本質上R認爲x
和y
長度不一樣,這是因爲它們是不同的類型。
@Prasad提供瞭解決方法,即將您提供給chisq.test
的2個數據幀取消列入向量。
但是,至少對我來說,使用這個函數的方式並沒有什麼意義。通常將數據存儲在列中,而不是數據框的行。它可能看起來沒有區別,但數據框的列是其組件,就像列表的組件一樣。每個單獨的組件(列)都是一個離散實體,是數據框中/ n /個觀測數據的一個向量。如果我們調換您df
(投下回的數據幀),以反映更自然的數據設置:
> df2 <- data.frame(t(df))
那麼我們就可以用你做的方法,但指數的第一列的不同的行df2
(而不是df
第一排的單獨的列)在chisq.test
呼叫:
> chisq.test(df2[1:3,1], df2[4:6,1])
Pearson's Chi-squared test
data: df2[1:3, 1] and df2[4:6, 1]
X-squared = 6, df = 4, p-value = 0.1991
Warning message:
In chisq.test(df2[1:3, 1], df2[4:6, 1]) :
Chi-squared approximation may be incorrect
這工作,因爲R是能夠丟棄空的尺寸在兩個子集,所以兩個輸入都是合適的載體長度:
> df2[1:3,1] ## drops the empty dimension!
[1] 1 2 3
> is.vector(df2[1:3,1])
[1] TRUE
我的預感,是它與姓名有關,但如果是這樣的話,錯誤信息並不是很有啓發性。 – 2011-01-19 20:21:06