长期潜伏者,通常使用SPSSgraphpad进行统计,缓慢但肯定地在学习如何使用R studio进行磨合。
在SPSS中,我有一个数据集,有三个变量:保险(分类,4个层次);npo_violation(分类,2个层次)和频率(标度,这个表示频率,例如,medicaid diddid not violate npo)。SPSS中的数据集示例
我试图尝试将这个带有频率计数变量的数据集带入r-studio中,这样我就可以根据组合的百分比来制作分组的条形图。
我已经使用 foreignhavenHmisc 将它带入 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))
我不知道怎样才能使countfrequency变量可以用来计算每个分类组合的百分比数。所以,例如,计算(然后绘制)"medicaid+no npo violation "和 "medicaid+yes npo violation "的百分比。
wtd.table(df_sample$insurance, df_sample$npo_violation, weights=wt)
但我知道这是不正确的,我收到错误信息 "Error in match.arg(type) : 'arg' must be NULL or a character vector"。
我非常害怕在这里发帖,但会非常感激任何帮助。使用R需要我花上一辈子的时间,但非常令人欣慰。谢谢。
下面是根据你的数据绘制的两张图。
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