r - r studio中的频率/计数变量
问题描述
长期潜伏者,通常使用 SPSS/graphpad 进行统计,缓慢但肯定地学习如何使用 R studio。
在 SPSS 我有一个包含三个变量的数据集:保险(分类,4 个级别);npo_violation(分类,2 个级别)和频率(规模,这表示例如医疗补助违反/未违反 npo 的频率)。SPSS中的示例数据集
我正在尝试将这个带有频率计数变量的数据集带入 r-studio,以便我可以根据组合的百分比制作分组条形图。
我已经使用 foreign/haven/Hmisc 将它带入 r studio 并自己创建了它
df_sample <- data.frame(insurance = c("Medicaid", "Medicaid", "Blue Cross", "Blue Cross",
"Managed Care", "Managed Care",
"Other", "Other"),
npo_violation=c("No", "Yes",
"No", "Yes",
"No", "Yes",
"No", "Yes"),
wt=c(18075, 438, 14691, 109, 6006, 53, 3098, 25))
我不确定如何使计数/频率变量可用于计算每个分类组合的百分比/计数。因此,例如,计算(然后绘制)我尝试使用 wtd.table 函数的“医疗补助+无 npo 违规”和“医疗补助+是 npo 违规”的百分比
wtd.table(df_sample$insurance, df_sample$npo_violation, weights=wt)
但我知道这是不正确的,并且我收到错误“match.arg(type) 中的错误:'arg' 必须为 NULL 或字符向量”。
我很害怕在这里发帖,但非常感谢任何帮助。使用 R 花了我很长时间,但非常令人欣慰。谢谢。
编辑:最终,我想绘制 x 轴:两个变量,“否”和“是”。传说将有 4 个类别:医疗补助、蓝十字、管理式医疗、其他。y 轴将是每个保险组在“是”和“否”中所占的百分比,如我在 spss 中制作的交叉表所示
解决方案
这是基于您的数据的两个图:
library(dplyr)
library(magrittr)
library(ggplot2)
df_sample %>%
mutate(percent=wt/sum(wt)) %>% # calculates percent
ggplot() + # launches plotter
geom_bar(aes(x=insurance, y=percent, fill=npo_violation),
stat="identity",position=position_dodge()) # bars
这会产生:
在上面的示例中,您可以交换变量x
并fill
获得相反的分组。你也可以这样做:
df_sample %>%
mutate(tag=paste(insurance, npo_violation)) %>% # combines labels
mutate(percent=wt/sum(wt)) %>% # calculates percent
ggplot(aes(x=tag,y=percent)) + # launches plotter
geom_bar(stat="identity") + # tells it to take wt literally
theme(axis.text.x=element_text(angle=45, hjust=1)) # x axis labels
推荐阅读
- python - 防止“除以零错误”的方法
- javascript - 如何从Javascript中的对象获取所有键名
- c# - Swashbuckle 可以为包含对象集合的表单生成正确的 OpenAPI 定义吗?
- java - 请解释这个 JAVA 程序的意外输出
- quantlib - Quantlib FixedRateBond 现金流
- maven - 无法从 Maven 和 NPM 的中央存储库中提取一些包
- reactjs - 在 React Context / Provider 中刷新 REST API
- python - 如何创建 PyTorch 可变张量?
- gdb - GDB:有什么方法可以构造“本地”方便的变量吗?
- r - 有没有办法同时显示许多 R xaringan 幻灯片(如 PowerPoint 幻灯片分类器)