考虑以下数据帧:
col1 | col2
1 | 1
1 | 2
1 | 3
2 | 4
2 | 5
2 | 6
我想要一个新列,例如数据帧中的
col3
,它具有以下定义:ith
元素col3[i]
是col2[j]
的所有值的平均值,对于所有j来说是col1[i] == col1[j] && i!=j
。for循环如下所示:
for (i in 1:length(data$col2))
{
sum = 0
count = 0
for (j in 1:length(data$col1))
{
if (data$col1[j] == data$col1[i] && i!=j)
{
sum = sum + data$col2[j]
count = count + 1
}
}
data$col3[i] = sum/count
}
决赛桌是:
col1 | col2 | col3
1 | 1 | 2.5
1 | 2 | 2
1 | 3 | 1.5
2 | 4 | 5.5
2 | 5 | 5
2 | 6 | 4.5
我可以使用apply函数,但这将花费我与for循环差不多的时间,对吗?感谢提供此循环的 vector 化版本的任何帮助。
最佳答案
您可以使用dplyr
:
library(dplyr)
dat %>% group_by(col1) %>%
mutate(col3 = (sum(col2) - col2)/(n()-1))
Source: local data frame [6 x 3]
Groups: col1 [2]
col1 col2 col3
(int) (int) (dbl)
1 1 1 2.5
2 1 2 2.0
3 1 3 1.5
4 2 4 5.5
5 2 5 5.0
6 2 6 4.5