考虑到这个
data.frame
:set.seed(4)
df <- data.frame(x = rep(1:5, each = 2), y = sample(50:100, 10, T))
# x y
# 1 1 78
# 2 1 53
# 3 2 93
# 4 2 96
# 5 3 61
# 6 3 82
# 7 4 53
# 8 4 76
# 9 5 91
# 10 5 99
我希望编写一些简单的函数(即特征工程),为变量x
创建特征,然后将每个生成的data.frame
合并在一起。例如:
library(dplyr)
count_x <- function(df) df %>% group_by(x) %>% summarise(count_x = n())
sum_y <- function(df) df %>% group_by(x) %>% summarise(sum_y = sum(y))
mean_y <- function(df) df %>% group_by(x) %>% summarise(mean_y = mean(y))
# and many more...
使用plyr::join_all
可以实现这一目标,但我想知道是否有更好(或性能更高)的方法,例如dplyr
或data.table
?
df_with_features <- plyr::join_all(list(count_x(df), sum_y(df), mean_y(df)),
by = 'x', type = 'full')
# > df_with_features
# x count_x sum_y mean_y
# 1 1 2 131 65.5
# 2 2 2 189 94.5
# 3 3 2 143 71.5
# 4 4 2 129 64.5
# 5 5 2 190 95.0
df %>% group_by(x) %>% summarise(count_x = n(), sum_y = sum(y), mean_y = mean(y))
。这一步操作即可完成所有列的处理。 - jeremycgsummarise
的调用将无法工作(或者至少在维护方面更加困难的情况下)。 - JasonAizkalnsReduce
和merge
的例子:http://stackoverflow.com/a/33031393/2204410 - Jaap