根据 R 中的标准计算平均值
calculate a mean by criteria in R
我想通过引入特定标准来计算 R 中的样本均值。例如,我有这个 table 并且我只想要那些 stage = 1 或 2:
的人的手段
treatment session period stage wage_accepted type
1 1 1 1 25 low
1 1 1 3 19 low
1 1 1 3 15 low
1 1 1 2 32 high
1 1 1 2 13 low
1 1 1 2 14 low
1 1 2 1 17 low
1 1 2 4 16 low
1 1 2 5 21 low
在这种情况下所需的输出应该是:
stage mean
1 21.0
2 19.6667
提前致谢。
您可以执行此操作,然后根据您的要求筛选阶段
# Calculating mean with respect to stages
df = do.call(rbind, lapply(split(data, f = data$stage),function(x) out = data.frame(stage = unique(x$stage), mean = mean(x$wage_accepted))))
# mean for stage 1 and 2
required = subset(df, stage %in% c(1,2))
使用 dplyr
库
library(dplyr)
df %>% filter(stage==1 | stage ==2) %>% group_by(stage) %>%
summarise(mean=mean(wage_accepted))
如果你是新手dplyr
稍微解释一下:
取数据框 df
然后 filter
其中 stage
等于 1 或 2。然后对于 stage
中的每个 group
计算 mean
的 wage_accepted
假设您有数据的 csv 文件,您可以使用以下方法将数据读入数据框:
data<-read.csv("PATH_TO_YOUR_CSV_FILE/Name_of_the_CSV_File.csv")
然后你可以根据sapply()
:
使用这段代码
sapply(split(data$Wage_Accepted,data$Stage),mean)
1 2 3 4 5
21.00000 19.66667 17.00000 16.00000 21.00000
或此代码依赖tapply()
:
tapply(data$Wage_Accepted,data$Stage,mean)
1 2 3 4 5
21.00000 19.66667 17.00000 16.00000 21.00000
检查一下。这是一个玩具示例,但 data.table 非常紧凑。 dplyr 显然也很棒。
library(data.table)
dat <- data.table(iris)
dat[Species == "setosa" | Species == "virginica", mean(Sepal.Width), by = Species]
就您对速度的需求而言... data.table 是一艘火箭飞船,请查找。我将留给您将其应用于您的问题。最好的,M2K
我想通过引入特定标准来计算 R 中的样本均值。例如,我有这个 table 并且我只想要那些 stage = 1 或 2:
的人的手段treatment session period stage wage_accepted type
1 1 1 1 25 low
1 1 1 3 19 low
1 1 1 3 15 low
1 1 1 2 32 high
1 1 1 2 13 low
1 1 1 2 14 low
1 1 2 1 17 low
1 1 2 4 16 low
1 1 2 5 21 low
在这种情况下所需的输出应该是:
stage mean
1 21.0
2 19.6667
提前致谢。
您可以执行此操作,然后根据您的要求筛选阶段
# Calculating mean with respect to stages
df = do.call(rbind, lapply(split(data, f = data$stage),function(x) out = data.frame(stage = unique(x$stage), mean = mean(x$wage_accepted))))
# mean for stage 1 and 2
required = subset(df, stage %in% c(1,2))
使用 dplyr
库
library(dplyr)
df %>% filter(stage==1 | stage ==2) %>% group_by(stage) %>%
summarise(mean=mean(wage_accepted))
如果你是新手dplyr
稍微解释一下:
取数据框 df
然后 filter
其中 stage
等于 1 或 2。然后对于 stage
中的每个 group
计算 mean
的 wage_accepted
假设您有数据的 csv 文件,您可以使用以下方法将数据读入数据框:
data<-read.csv("PATH_TO_YOUR_CSV_FILE/Name_of_the_CSV_File.csv")
然后你可以根据sapply()
:
sapply(split(data$Wage_Accepted,data$Stage),mean)
1 2 3 4 5
21.00000 19.66667 17.00000 16.00000 21.00000
或此代码依赖tapply()
:
tapply(data$Wage_Accepted,data$Stage,mean)
1 2 3 4 5
21.00000 19.66667 17.00000 16.00000 21.00000
检查一下。这是一个玩具示例,但 data.table 非常紧凑。 dplyr 显然也很棒。
library(data.table)
dat <- data.table(iris)
dat[Species == "setosa" | Species == "virginica", mean(Sepal.Width), by = Species]
就您对速度的需求而言... data.table 是一艘火箭飞船,请查找。我将留给您将其应用于您的问题。最好的,M2K