C. Denney
C. Denney

Reputation: 627

Replicate dlply() funcationality in dplyr

The plyr package has a variety of _ply functions in which the first two letters refer to the input and output so that ddply takes a dataframe input and produces a dataframe output, and dlply takes a dataframe input and produces a list output. For a variety of reasons I generally prefer to use the dplyr package and plyr and dplyr do not work well together in a single environment. Is there a way to replicate the "data frame in, list out" functionality of the dlply function from plyr in the piping syntax of dplyr?

A simple example of the functionality I would like to replicate:

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")

The code I would like to write is something along the lines of this:

spline_list = data %>%
    group_by(group_var) %>%
    list_mutate(list_element = spline.fun, xvar = x, yvar = y)

but as far as I know, there is not a dplyr function that creates a list element the way that mutate creates a new column

Upvotes: 2

Views: 928

Answers (1)

www
www

Reputation: 39184

We can split the data frame by group_var, use map from the package to apply your function.

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

Upvotes: 2

Related Questions