为了找到 SD 而按组排序的问题

问题描述 投票:0回答:1

我正在尝试使用按组汇总功能来按组创建置信区间。当我仅使用它的平均值运行代码时,它可以工作,但是当我添加代码以获取

summarize()
中的错误: ℹ 在争论中:
N_autonomous = n(autonomous)
。 ℹ 第 1 组:
yeargroup = 5
。 由
n()
中的错误引起: !未使用的参数(自主)

我运行了这段代码,希望获得每组的 SD

auto_means <- motivation %>%  
  group_by(yeargroup) %>%  
  summarize(mean_autonomous=mean(autonomous),
            sd_autonomous=sd(autonomous),
            N_autonomous= n(autonomous),
            se=sd_autonomous/sqrt(N_autonomous),
            upper_limit=mean_autonomou+se,
            lower_limit=mean_autonomou-se 
)

ggplot2 group-by standard-deviation
1个回答
0
投票

您收到该错误是因为

n()
返回您分组所依据的每个组中的人数(即
yeargroup
)。因此,如果您想查找
yeargroup
中的个体数量,如果您已经按
n()
进行分组,只需用空参数指定
yeargroup
即可。有关更多详细信息,请参阅帮助文件(即
?n()
)。

set.seed(1)
data<-data.frame(
  group=rep(1:10,times=1,each=5),
  year=rep(1:5,times=10,each=1),
  x=rnorm(50)
)
library(tidyverse)
auto_means <- data %>%  
  group_by(year) %>%  
  summarize(mean_x=mean(x),
            sd_x=sd(x),
            N_year=n(),
            se=sd_x/sqrt(N_year),
            upper_limit=mean_x+se,
            lower_limit=mean_x-se 
  )

此外,您始终可以使用

length()
而不是
n()
来获取不同组中的人数(尽管他们应该给您相同的数字)。

set.seed(1)
auto_means <- data %>%  
  group_by(year) %>%  
  summarize(mean_x=mean(x),
            sd_x=sd(x),
            N_x=length(x) 
  )
© www.soinside.com 2019 - 2024. All rights reserved.