FMM
FMM

Reputation: 2015

Apply different data to a function in R

I have the following data frame:

library(tidyverse)

set.seed(1234)

df <- data.frame(
  x = seq(1, 100, 1),
  y = rnorm(100)
)

Where I apply a smooth spline using different knots:

nknots <- seq(4, 15, 1)

output <- map(nknots, ~ smooth.spline(x = df$x, y = df$y, nknots = .x))

What I need to do now is to apply the same function using 2-point and 3-point averages:

df_2 <- df %>% 
  group_by(., x = round(.$x/2)*2) %>%
  summarise_all(funs(mean))

df_3 <- df %>% 
  group_by(., x = round(.$x/3)*3) %>%
  summarise_all(funs(mean))

In summary, I need to apply the function I used in output with the following data frames:

Of course, this is a minimal example, so I am looking for a efficient way of doing it. Preferably with the purrr package.

Upvotes: 1

Views: 57

Answers (2)

AntoniosK
AntoniosK

Reputation: 16121

Here's one possible solution:

library(tidyverse)

set.seed(1234)

df <- data.frame(x = seq(1, 100, 1),
                 y = rnorm(100))

# funtion to get v-point averages
GetAverages = function(v) {
  df %>% 
    group_by(., x = round(.$x/v)*v) %>%
    summarise_all(funs(mean)) }

# specify nunber of knots
nknots <- seq(4, 15, 1)


dt_res = tibble(v=1:3) %>%                     # specify v-point averages
  mutate(d = map(v, GetAverages)) %>%          # get data for each v-point 
  crossing(., data.frame(nknots=nknots)) %>%   # combine each dataset with a knot
  mutate(res = map2(d, nknots, ~smooth.spline(x = .x$x, y = .x$y, nknots = .y)))  # apply smooth spline

You can use dt_res$res[dt_res$v == 1] to see all results for your original daatset, dt_res$res[dt_res$v == 2] to see results for your 2-point estimate, etc.

Upvotes: 1

denis
denis

Reputation: 5673

Using lapply, and the library zoo to calculate the moving average in a more simple and elegant manner:

library(zoo)

lapply(1:3,function(roll){
  dftemp <- as.data.frame(rollmean(df,roll))
  map(nknots, ~ smooth.spline(x = dftemp$x, y = dftemp$y, nknots = .x))
  })

Upvotes: 2

Related Questions