【问题标题】:error creating chisq.test() in R - invalid 'type' (character) of argument在 R 中创建 chisq.test() 时出错 - 参数的“类型”(字符)无效
【发布时间】:2014-11-04 05:17:28
【问题描述】:

我正在创建一个名为 Comp1 的 data.frame 独立性卡方检验,其中包含两个二进制变量和 13109 obs。

在根据人口统计数据对消费者进行聚类之前,我正在使用该测试。如果这两个变量相互依赖,那么某些值将在一个簇中。这两个变量是另一个 data.frame 的子集,有 36 个变量。

我收到一条错误消息,提示 data.framecharacter 变量,而不是 str() 函数显示的 factors

为什么错误提示 data.frame 具有 character 值?

数据:

> str(Comp1)
'data.frame':   13109 obs. of  2 variables:
 $ HomeOwnerStatus: Factor w/ 2 levels "Own","Rent": 1 2 2 2 1 2 1 1 2 2 ...
 $ MaritalStatus  : Factor w/ 2 levels "Married","Single": 2 1 1 1 2 1 2 1 1 1 ...

示例:

> #Create dataset
> homeownerstatus <- c("Own", "Rent", "Own", "Own", "Rent", "Own")
> maritalstatus <- c("Married", "Married", "Married", "Single", "Single", "Married")
> Comp1 <- data.frame(homeownerstatus, maritalstatus)

解决方案出错:

> #Test binary variables for independence 
> #Create matrix from data.frame
> DF4 <- as.matrix(Comp1)
> #Comparison of marital status and home owner status
> #Perform chi-squared test for independence of two variables
> chisq.test(table(Comp1))

    Chi-squared test for given probabilities

data:  table(DF4)
X-squared = 295149.5, df = 71, p-value < 2.2e-16

【问题讨论】:

    标签: r chi-squared


    【解决方案1】:

    chisq.test either 想要 bothxy 参数的因子向量matrixdata.frame 用于x 参数。当 data.frame 被传递时,它会被函数 as.matrix 转换为 matrix。此步骤将 data.frame 中的因子列强制转换为字符。

    > as.matrix(Comp1)
         homeownerstatus maritalstatus
    [1,] "Own"           "Married"    
    [2,] "Rent"          "Married"    
    [3,] "Own"           "Married"    
    [4,] "Own"           "Single"     
    [5,] "Rent"          "Single"     
    [6,] "Own"           "Married"
    

    所以,我的建议是传递两个因子向量:

    chisq.test(Comp1$homeownerstatus, Comp1$maritalstatus)
    
            Pearson's Chi-squared test with Yates' continuity correction
    
    data:  Comp1$homeownerstatus and Comp1$maritalstatus
    X-squared = 0, df = 1, p-value = 1
    
    Warning message:
    In chisq.test(Comp1$homeownerstatus, Comp1$maritalstatus) :
      Chi-squared approximation may be incorrect
    

    编辑

    当您将矩阵或 data.frame 传递给 x 参数时,该对象将被视为列联表,这不是您想要的。您有两个二进制变量,应计算其列联表,然后根据卡方检验进行测试。因此,您应该如上所述传递每个因子向量,或者,计算列联表并将其传递给chisq.test

    chisq.test(table(Comp1))
    

    【讨论】:

    • 将可重现的示例转换为矩阵有效,但不适用于我的数据集。我又犯了一个错误。请查看我的编辑。
    • 没关系,我使用了您的编辑,它有效。谢谢!
    猜你喜欢
    • 2022-09-29
    • 2021-05-04
    • 2016-08-07
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多