如何在R语言中生成多选交叉表并去除行首的TRUE/FALSE标识
解决expss交叉表行首显示TRUE/FALSE的问题
嘿,我之前用expss做交叉表的时候也遇到过这个烦人的问题!你现在的代码里,tab_cells()直接用了逻辑判断(比如qpd4_1==1),expss会默认把这些逻辑向量的两个取值(TRUE/FALSE)都作为行标签的一部分显示出来。要只保留你自定义的文本(比如"By phone"),可以试试下面两种方法:
方法1:先创建带标签的指标变量(更清晰易维护)
这种方法先把每个逻辑判断转换成带自定义标签的变量,后续生成表格时就只会显示你设置的标签:
library(expss) library(haven) X4707 <- read_sav("/home/cfmc/4707/data/4707.sav") # 创建指标变量并设置自定义标签 X4707 <- X4707 %>% mutate( by_phone = qpd4_1 == 1, by_email = qpd4_2 == 1, utility_website = qpd4_3 == 1, roseville_notification = qpd4_4 == 1, social_media = qpd4_5 == 1, text = qpd4_6 == 1, not_sure = qpd4_8 == 1 ) %>% apply_labels( by_phone = "By phone", by_email = "By email", utility_website = "Utility website", roseville_notification = "Roseville Electric notification", social_media = "Social media", text = "Text", not_sure = "Not sure" ) # 生成交叉表,只计算TRUE对应的百分比并隐藏空行 X4707 %>% tab_cells(by_phone, by_email, utility_website, roseville_notification, social_media, text, not_sure) %>% tab_cols(total(), qf5) %>% tab_stat_cpct(only_values = TRUE) %>% # 只保留TRUE的统计值 tab_last_sig_cpct() %>% tab_pivot(drop_empty_rows = TRUE)
方法2:直接在tab_cells里处理(更简洁)
如果你不想额外创建变量,可以直接在tab_cells()里用as.category()给逻辑值指定唯一的标签,同时过滤掉FALSE对应的空行:
library(expss) library(haven) X4707 <- read_sav("/home/cfmc/4707/data/4707.sav") X4707 %>% tab_cells( "By phone" = as.category(qpd4_1 == 1, labels = c("By phone" = TRUE)), "By email" = as.category(qpd4_2 == 1, labels = c("By email" = TRUE)), "Utility website" = as.category(qpd4_3 == 1, labels = c("Utility website" = TRUE)), "Roseville Electric notification" = as.category(qpd4_4 == 1, labels = c("Roseville Electric notification" = TRUE)), "Social media" = as.category(qpd4_5 == 1, labels = c("Social media" = TRUE)), "Text" = as.category(qpd4_6 == 1, labels = c("Text" = TRUE)), "Not sure" = as.category(qpd4_8 == 1, labels = c("Not sure" = TRUE)) ) %>% tab_cols(total(), qf5) %>% tab_stat_cpct() %>% tab_last_sig_cpct() %>% tab_pivot(drop_empty_rows = TRUE) # 去掉FALSE对应的空行
这两种方法都能让你的交叉表行区域(stub)只显示你设置的自定义文本,再也看不到TRUE/FALSE啦!
内容的提问来源于stack exchange,提问作者larryb
相关产品推荐
相关产品推荐

