plyr
包具有多种_ply
函数,其中前两个字母表示输入和输出,以便ddply
获取数据帧输入并生成数据帧输出,以及dlply
获取数据框输入并生成列表输出。出于各种原因,我通常更喜欢使用dplyr
包,而plyr
和dplyr
在单个环境中无法很好地协同工作。有没有办法在dlply
的管道语法中从plyr
复制dplyr
函数的“数据框,列出”功能?
我想要复制的功能的一个简单示例:
data = data.frame(x = rep(seq(from = 1, to = 100, by = 1), times = 3),
y = rnorm(n = 300),
group_var = c(rep("A", 100), rep("B", 100), rep("C", 100)))
spline.fun = function(x, xvar, yvar, ...) {
smooth.spline(x = x[,xvar], y = x[,yvar], ...)
}
spline_list = dlply(data, "group_var", spline.fun, xvar = "x", yvar = "y")
我想写的代码就是这样的:
spline_list = data %>%
group_by(group_var) %>%
list_mutate(list_element = spline.fun, xvar = x, yvar = y)
但据我所知,没有dplyr
函数以mutate创建新列的方式创建列表元素
答案 0 :(得分:2)
我们可以按group_var
拆分数据框,使用purrr包中的map
来应用您的功能。
library(tidyverse)
data2 <- data %>%
split(f = data$group_var) %>%
map(~spline.fun(.x, xvar = "x", yvar = "y"))
# $`A`
# Call:
# smooth.spline(x = x[, xvar], y = x[, yvar])
#
# Smoothing Parameter spar= 1.315545 lambda= 14.95228 (20 iterations)
# Equivalent Degrees of Freedom (Df): 2.016214
# Penalized Criterion (RSS): 74.08271
# GCV: 0.7716288
#
# $B
# Call:
# smooth.spline(x = x[, xvar], y = x[, yvar])
#
# Smoothing Parameter spar= 1.499963 lambda= 321.1298 (29 iterations)
# Equivalent Degrees of Freedom (Df): 2.000764
# Penalized Criterion (RSS): 77.98068
# GCV: 0.8119731
#
# $C
# Call:
# smooth.spline(x = x[, xvar], y = x[, yvar])
#
# Smoothing Parameter spar= 1.499953 lambda= 321.0788 (27 iterations)
# Equivalent Degrees of Freedom (Df): 2.000764
# Penalized Criterion (RSS): 104.8997
# GCV: 1.092268