0

my data set is:

mydata <- data.frame(
  x1= as.factor(1:3), 
  x2= as.factor (4:6), 
  x3= as.factor(7:9), 
  x4= as.factor (2:7), 
  x5= as.factor(1:6), 
  x6= as.numeric(1:18),
  x7= as.numeric(18:35)
  )

I want to do a spline on x6 and x7, but before I group x1,x2, x3, x4, x5, i do:

mydata1 <- mydata%>%
    nest(-(x1:x5))%>%
    mutate(fit = map(data, ~spline(.$x6,.$x7)))

now I want to use broom::augment, but spline is a list. another problem is that I want to do a plot (with ggplot2):

ggplot(data= mydata%>%, aes(x = x6, y = x7))+
    geom_line(aes(color = x1, linetype = x2))+
    geom_line(data= mydata1$fit, aes(x= .$x, y= .$y,color = x1,linetype = x2))+
    facet_grid(x3~x4, scales = "free")

but give me an error:"Error: ggplot2 doesn't know how to deal with data of class list", beacuse ggplot wants a dataframe and not list. is there a method to have fit as dataframe or to use augment on list? if I can use augment, I can do this:

mydata1 <- mydata%>%
    nest(-(x1:x5))%>%
    mutate(fit = map(data, ~spline(.$x6,.$x7)),
           result = map(fit, augment))%>%
    unnest(result)

and so I have .fitted in a dataframe and I can use ggplot.

memy
  • 229
  • 1
  • 2
  • 8

1 Answers1

0

I think this is what you're looking for:

library(ggplot2)
library(tidyverse)

data_frame(
  x1=as.factor(1:3), 
  x2=as.factor (4:6), 
  x3=as.factor(7:9), 
  x4=as.factor (2:7), 
  x5=as.factor(1:6), 
  x6=as.numeric(1:18),
  x7=as.numeric(18:35)
) -> mydata

mydata %>%
  nest(-(x1:x5))%>%
  mutate(fit=map(data, ~as_data_frame(spline(.$x6, .$x7)))) -> mydata1

At this point, mydata$fit is a column of data frames with x and y columns.

You can do this for the plotting:

ggplot() +
  geom_line(data=mydata, 
            aes(x=x6, y=x7, color=x1, linetype=x2))+
  geom_line(data=select(mydata1, -data) %>% unnest(fit), 
            aes(x=x, y=y, color=x1, linetype=x2)) +
  facet_grid(x3~x4, scales="free") 
hrbrmstr
  • 77,368
  • 11
  • 139
  • 205