这是我到目前为止设置的代码:
library(dslabs)
library(dplyr)
library(lubridate)
data("reported_heights")
dat <- mutate(reported_heights, date_time = ymd_hms(time_stamp)) %>%
filter(date_time >= make_date(2016, 01, 25) & date_time < make_date(2016, 02, 1)) %>%
mutate(type = ifelse(day(date_time) == 25 & hour(date_time) == 8 & between(minute(date_time), 15, 30), "inclass","online")) %>%
select(sex, type, time_stamp)
y <- factor(dat$sex, c("Female", "Male"))
x <- dat$type
counter <- count(dat, sex,type)
它为我创建了一个tbl_df,看起来像这样,链接如下:
sex | type | n
1 Female | inclass | 26
2 Male | inclass | 13
3 Female | online | 42
4 Male | online | 69
我问您是否可以通过代码来计算每种性别在每种班级中所占的比例。
我一直在尝试使用x字符“ inclass”和“ online”作为列创建新表,并添加了比例列,然后将y因子“ male”和“ female”作为行。我一直在尝试使用pull()
和prop.table()
来做到这一点,但是我是一个新手,如果您的美丽专家可以帮助我,那对我来说将意味着整个世界。我已经回答了几个小时,也许答案已经在那里了,所以请原谅我似乎找不到它...。非常感谢。
在每种类型的课堂(在线和课堂)中性别(男性和女性)的比例是多少?
可以通过将性别除以给定类的学生总数来计算。
例如:在(42 + 69)= 111中,有42位女性在网上学习。答:在网络课堂上,女性占38%。
我们如何在R中做到这一点?
您可以使用table()
,
my.table <- with(dat, table(sex, type))
my.table
# type
# sex inclass online
# Female 26 42
# Male 13 69
和apply()
结果的一个函数。
res <- apply(my.table, 2, function(x) x/sum(x)*100)
res
# type
# sex inclass online
# Female 66.66667 37.83784
# Male 33.33333 62.16216
要获得更好的输出,可以先round()
然后添加%
。
res2 <- as.data.frame(unclass(round(res, 1)))
res2[] <- lapply(res2, paste0, "%")
res2
# inclass online
# Female 66.7% 37.8%
# Male 33.3% 62.2%
要获得每个类别中的比例,我们可以在基数R中使用ave
df$prop <- with(df, n/ave(n, type, FUN = sum)) * 100
df
# sex type n prop
#1 Female inclass 26 66.66667
#2 Male inclass 13 33.33333
#3 Female online 42 37.83784
#4 Male online 69 62.16216
[dplyr
也可以实现
library(dplyr)
df %>% group_by(type) %>% mutate(prop = n/sum(n) * 100)
和data.table
library(data.table)
setDT(df)[, prop := n/sum(n) * 100, by = type]
数据
df <- structure(list(sex = structure(c(1L, 2L, 1L, 2L), .Label = c("Female",
"Male"), class = "factor"), type = structure(c(1L, 1L, 2L, 2L
), .Label = c("inclass", "online"), class = "factor"), n = c(26L,
13L, 42L, 69L)), class = "data.frame", row.names = c(NA, -4L))