小编Can*_*ner的帖子

如何使用summarise_each计算加权平均值?

如何使用dplyr中的summarise_each计算数据集中所有字段的加权平均值?例如,假设我们想要通过cylmtcars数据集进行分组,并计算权重作为齿轮列的所有列的加权平均值.我尝试了以下但是无法让它工作.

mtcars %>% group_by(cyl) %>% summarise_each(funs(weighted.mean(., gear)))

# The line above gives the following output
# Error in weighted.mean.default(c(1, 2, 2, 1, 2, 1, 1, 1, 2, 2, 2), 4.15555555555556) : 
# 'x' and 'w' must have the same length
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助!

r dplyr

5
推荐指数
1
解决办法
4539
查看次数

我们如何在单个图表中使用多个geom_smooth?

我想geom_smooth在单个 ggplot2 图表中使用多个图层。当我尝试这样做时,配色方案就搞砸了。这是一个演示正在发生的事情的示例。

我们构建一个我们想要可视化的简单数据框。

df = data.frame(x = c("a", "b", "c"),
             y1 = seq(1, 3),
             y1_upr = seq(2, 4),
             y1_lwr = seq(0, 2),
             y2 = seq(2, 4),
             y2_upr = seq(2.5, 4.5),
             y2_lwr = seq(1.5, 3.5))
Run Code Online (Sandbox Code Playgroud)

我们可以轻松地可视化 y1 和 y2。

plot_obj = ggplot(data = df, aes(x = x, group = 1)) + 
  geom_line(aes(y = y1, colour = "y1")) + 
  geom_line(aes(y = y2, colour = "y2")) +     
  scale_colour_manual("", breaks = c("y1", "y2"), values = c("blue", "red"))
plot_obj
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 如果我们添加 1 geom_smooth …

r ggplot2

1
推荐指数
1
解决办法
2万
查看次数

标签 统计

r ×2

dplyr ×1

ggplot2 ×1