创建基于df中其他两个变量的一个变量的平均值表

时间:2019-08-28 09:59:21

标签: r

我有3个变量BSP,HEEL和COR。我想创建一个表,以将BSP分组为行,将BSP分组为HEEL来查看结果。对于给定的BSP和HEEL组,其细胞具有平均COR。

这是我到目前为止创建的代码:

lg$heel_group <- cut(lg$Heel, breaks = c( -20 ,-10,-2, 2,10,20),
                     labels = c("-20", "-10", "0", "10", "20"))
lg$Bsp_group<- cut(lg$BSP, breaks = c( 0,5, 10, 15, 20, 25),
                   labels = c( "5", "10", "15", "20", "25"))

heel_bsp <- select(lg, BspCor, heel_group, Bsp_group)

heel_bsp %>% 
  group_by(Bsp_group, heel_group) %>%    # Columns to group by
  summarise(value = round(mean(BspCor), digits = 2))%>%   # Calculate the mean of value
kable( escape = F)%>%
  kable_styling("hover", full_width = F, font_size =11)

 dput(head(heel_bsp))
structure(list(BspCor = c(0, 0.96, 0.92, 0.9, 0.89, 0.94), heel_group = structure(c(NA, 
3L, 3L, 3L, 3L, 3L), .Label = c("-20", "-10", "0", "10", "20"
), class = "factor"), Bsp_group = structure(c(NA, 2L, 2L, 2L, 
2L, 2L), .Label = c("5", "10", "15", "20", "25"), class = "factor")), row.names = c(NA, 
6L), class = "data.frame")

我得到的是一个线性表,该表显示了我想要的结果,但不是我想要的格式。其中的列以BSP组为标题,行以HEEL组为标题。

预期结果:

enter image description here

0 个答案:

没有答案