考虑以下数据集:
a <- c(1,23,18,47,15,56,67,43,9)
b <- c("A","B","B","C","C","B","D","A","C")
df <- data.frame(var1=a, var2=b)
我需要在df的子部分(基于var2值)上运行函数(例如mean()),如下所示:
df_A <- subset(df,var2=="A")
mean_A <- mean(df_A$var1)
df_B <- subset(df,var2=="B")
mean_B <- mean(df_B$var1)
df_C <- subset(df,var2=="C")
mean_C <- mean(df_C$var1)
df_D <- subset(df,var2=="D")
mean_D <- mean(df_D$var1)
我在这里面临的最大困难是我事先不知道var2中有多少个差值。在我的示例中,我有4种可能性:“ A”,“ B”,“ C”和“ D”。但实际上,它是随机的...有时我在var2中有一个具有2个差值的数据集,有时15个,有时更多...
我认为循环可能是一个很好的解决方案,但是我有点迷路了...
可以帮忙吗?预先感谢。
答案 0 :(得分:2)
最简单的方法是使用dplyr软件包
a <- c(1,23,18,47,15,56,67,43,9)
b <- c("A","B","B","C","C","B","D","A","C")
df <- data.frame(var1=a, var2=b)
library(dplyr)
df2 <- df %>%
group_by(var2) %>%
summarise(mean=mean(var1))
df2
#output
# # A tibble: 4 x 2
# var2 mean
# <fct> <dbl>
# 1 A 22
# 2 B 32.3
# 3 C 23.7
# 4 D 67