问题描述
这是我在这里的第一条消息。我正在尝试从edX R课程解决R练习,但我陷入其中。如果有人可以帮助我解决问题,那就太好了。这是给出的数据框和问题:
> students
height shoesize gender population
1 181 44 male kuopio
2 160 38 female kuopio
3 174 42 female kuopio
4 170 43 male kuopio
5 172 43 male kuopio
6 165 39 female kuopio
7 161 38 female kuopio
8 167 38 female tampere
9 164 39 female tampere
10 166 38 female tampere
11 162 37 female tampere
12 158 36 female tampere
13 175 42 male tampere
14 181 44 male tampere
15 180 43 male tampere
16 177 43 male tampere
17 173 41 male tampere
鉴于上面的数据框,请创建两个子集,其子集的学生的身高等于或低于中位数身高(称为 students.short ),其学生的身高严格高于中位数身高(称为 students.tall )。按人口划分的上述两个子集中的每个人的平均鞋码是多少?
我已经能够创建两个子集 students.tall 和 students.short (均显示TRUE/FALSE
的答案),但是我不知道不知道如何通过人口求平均值。数据应显示如下:
kuopio tampere
students.short xxxx xxxx
students.tall xxxx xxxx
非常感谢你能帮我忙!
解决方法
我们可以基于split
的高度通过逻辑矢量median
# // median height
medHeight <- median(students$height,na.rm = TRUE)
# // split the data into a list of data.frames using the 'medHeight'
lst1 <- with(students,split(students,height > medHeight))
然后使用list
中的aggregate
在base R
上循环
lapply(lst1,function(dat) aggregate(shoesize ~ population,data = dat,FUN = mean,na.rm = TRUE))
但是,我们不需要创建两个单独的数据集或一个list
。可以通过将“人口”和使用logical
向量创建的“ grp”分组来完成
library(dplyr)
students %>%
group_by(grp = height > medHeight,population) %>%
summarise(shoesize = mean(shoesize))
,
您可以尝试以下方法:
#Code
students.short <- students[students$height<=median(students$height),]
students.tall <- students[students$height>median(students$height),]
#Mean
mean(students.short$shoesize)
mean(students.tall$shoesize)
输出:
[1] 38.44444
[1] 42.75
,
您可以在pivot_wider()
中使用tidyr
并将参数values_fn
设置为mean
。
library(dplyr)
library(tidyr)
df %>%
mutate(grp = if_else(height > median(height),"students.tall","students.short")) %>%
pivot_wider(id_cols = grp,names_from = population,values_from = height,values_fn = mean)
# # A tibble: 2 x 3
# grp kuopio tampere
# <chr> <dbl> <dbl>
# 1 students.tall 176. 177.
# 2 students.short 164 163.
通过base
的方式,您可以尝试xtabs()
,它返回一个table
对象。
xtabs(height ~ grp + population,aggregate(height ~ grp + population,transform(df,grp = ifelse(height > median(height),"students.short"))))
# population
# grp kuopio tampere
# students.short 164.0000 163.4000
# students.tall 175.6667 177.2000
注意: 要将table
对象转换为data.frame
,可以使用as.data.frame.matrix()
。