我刚开始在R,我正试图把我的头脑围绕着一个大学的任务。
具体来说,我正在使用2018年通用社会调查数据集(代码本:https://www.thearda.com/Archive/Files/Codebooks/GSS2018_CB.asp),我试图弄清楚宗教对人们寻求心理健康帮助的方式是否有任何影响。
我想用reliten (宗教性的自我评估--从强烈到没有宗教)作为自变量,mentloth (询问有心理健康问题的人是否应该接触心理健康专业人士--是或否)作为因变量。在卡方旁边,我也想添加CrossTable(GSS18$reliten, GSS18$mentloth),但我不知道如何去掉编码为0、8和9的“不适用”、“不知道”和“没有响应”值。
下面是我的数据的简短预览,如果有帮助的话。
structure(list(reliten = structure(c(1, 1, 4, 1, 1, 2, 1, 1,
4, 2, 2, 3, 2, 2, 4, 1, 4, 3, 2, 1, 2, 1, 2, 2, 1), label = "Would you call yourself a strong [religious preference] or a not very strong [re", format.stata = "%8.0g", labels = c(`Not applicable` = 0,
Strong = 1, `Not very strong` = 2, `Somewhat strong` = 3, `No religion` = 4,
`Don't know` = 8, `No answer` = 9), class = c("haven_labelled",
"vctrs_vctr", "double")), mentloth = structure(c(0, 1, 0, 1,
2, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0
), label = "Should [NAME] go to a therapist, or counselor, like a psychologist, social worke", format.stata = "%8.0g", labels = c(`Not applicable` = 0,
Yes = 1, No = 2, `Don't know` = 8, `No answer` = 9), class = c("haven_labelled",
"vctrs_vctr", "double"))), row.names = c(NA, -25L), class = c("tbl_df",
"tbl", "data.frame"))任何帮助都将不胜感激!
发布于 2022-03-22 09:34:37
CrossTable函数来自gmodels包,它不知道如何处理类haven_labelled的对象,因此将它们视为数字向量。
为了获得更好的输出,您可以将它们转换为CrossTable保留名称的基本R因子。幸运的是,天堂包包含用于执行此操作的函数as_factor。
一旦您这样做了,就很容易降低您不想要的因子级别,如下所示:
library(gmodels)
library(haven)
df <- GSS18[!GSS18$mentloth %in% c(0, 8, 9),]
df$reliten <- as_factor(df$reliten)
df$mentloth <- as_factor(df$mentloth)
df$reliten <- factor(as.character(df$reliten),
levels = c("No religion", "Somewhat strong",
"Not very strong", "Strong"))所以现在你可以
CrossTable(df$reliten, df$mentloth)
Cell Contents
|-------------------------|
| N |
| Chi-square contribution |
| N / Row Total |
| N / Col Total |
| N / Table Total |
|-------------------------|
Total Observations in Table: 12
| df$mentloth
df$reliten | Yes | No | Row Total |
----------------|-----------|-----------|-----------|
No religion | 1 | 0 | 1 |
| 0.008 | 0.083 | |
| 1.000 | 0.000 | 0.083 |
| 0.091 | 0.000 | |
| 0.083 | 0.000 | |
----------------|-----------|-----------|-----------|
Somewhat strong | 1 | 0 | 1 |
| 0.008 | 0.083 | |
| 1.000 | 0.000 | 0.083 |
| 0.091 | 0.000 | |
| 0.083 | 0.000 | |
----------------|-----------|-----------|-----------|
Not very strong | 3 | 0 | 3 |
| 0.023 | 0.250 | |
| 1.000 | 0.000 | 0.250 |
| 0.273 | 0.000 | |
| 0.250 | 0.000 | |
----------------|-----------|-----------|-----------|
Strong | 6 | 1 | 7 |
| 0.027 | 0.298 | |
| 0.857 | 0.143 | 0.583 |
| 0.545 | 1.000 | |
| 0.500 | 0.083 | |
----------------|-----------|-----------|-----------|
Column Total | 11 | 1 | 12 |
| 0.917 | 0.083 | |
----------------|-----------|-----------|-----------|https://stackoverflow.com/questions/71569460
复制相似问题