例如,如果我的数据看起来像这样:
Group Smoker
1 Ex
1 None
1 None
2 Current
1 Current
2 Ex
2 None我想计算第一组中前吸烟者、无吸烟者和当前吸烟者的百分比或数量,以及第二组中前吸烟者、无吸烟者和当前吸烟者的百分比或数量
有没有简单的代码可以做到这一点?
发布于 2018-04-23 00:15:45
我们可以使用dplyr包来计算计数和百分比。
library(dplyr)
# Count
dat2 <- dat %>%
count(Group, Smoker)
dat2
# # A tibble: 6 x 3
# Group Smoker n
# <int> <chr> <int>
# 1 1 Current 1
# 2 1 Ex 1
# 3 1 None 2
# 4 2 Current 1
# 5 2 Ex 1
# 6 2 None 1
# Percentage
dat3 <- dat2 %>%
group_by(Group) %>%
mutate(Percent = n/ sum(n) * 100) %>%
ungroup()
dat3
# # A tibble: 6 x 4
# Group Smoker n Percent
# <int> <chr> <int> <dbl>
# 1 1 Current 1 25.0
# 2 1 Ex 1 25.0
# 3 1 None 2 50.0
# 4 2 Current 1 33.3
# 5 2 Ex 1 33.3
# 6 2 None 1 33.3DATA
dat <- read.table(text = "Group Smoker
1 Ex
1 None
1 None
2 Current
1 Current
2 Ex
2 None",
header = TRUE, stringsAsFactors = FALSE)https://stackoverflow.com/questions/49968031
复制相似问题