Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

ggplot2 - Function do ({}) in R does not allow me to name "ode" to be able to add the variables inside ggplot mapings

I am implementing SIR model in R, I need to vary beta and gamma for it.

library(deSolve)

par(mar = rep(2, 4))
N = 1000
vi <- c(S = N-1,I = 1,R = 0)

SIR <- function(t, vi, pm) {
  with(as.list(c(vi, pm)), {
    
    ds <- -beta* S* (I/N) 
    di <-  beta* S* (I/N) - gamma * I 
    dr <-  gamma * I
    
    return(list(c(ds, di, dr)))
  })
  
}

t <- seq(0, 50, by = 1)


betavals <- c(1,5,8)
ipvals <- c(2,20,50)
gammavals <- 1/ipvals

However, when wanting to apply the function for my different Beta and gamma values, the do ({}) function does not allow me to name my function "ode" and thus be able to print in ggplot (aes (x = t, y = value ) both I, S and R.

library(tidyverse)

expand.grid(beta=betavals,gamma=gammavals)%>%
  group_by(beta,gamma) %>%
  do(
    {
      ode(func=SIR,y=vi,times=t,
          parms=c(beta=.$beta,gamma=.$gamma)) %>%
        as.data.frame() -> out
      
    }
  ) out %>%
  
  gather(variable,value,-time)%>%
  ggplot(aes(x=time,y=value,color=variable))+ #value is I,S,R 
  geom_line()+
  facet_grid(beta~gamma,scales='free_y',labeller=label_both)+
  theme_bw()

When doing so I get this error

<Error: unexpected symbol in:
"    }
  ) out">

I thank you in advance for your help and time.

question from:https://stackoverflow.com/questions/65661088/function-do-in-r-does-not-allow-me-to-name-ode-to-be-able-to-add-the-vari

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You do not have access to out variable outside do function. We can continue using the same chain operation to get data in long format. gather has been retired so I replace it with pivot_longer.

library(tidyverse)
library(deSolve)

expand.grid(beta=betavals,gamma=gammavals)%>%
  group_by(beta,gamma) %>%
  do(
    {
      ode(func=SIR,y=vi,times=t,
          parms=c(beta=.$beta,gamma=.$gamma)) %>%
        as.data.frame()
    }
  ) %>%
  ungroup %>%
  pivot_longer(cols = S:R) %>%
  mutate(name = factor(name, c('S', 'I', 'R'))) %>%
  ggplot(aes(x=time,y=value,color=name))+ 
  geom_line() + 
  facet_grid(beta~gamma,scales='free_y',labeller=label_both)+
  theme_bw()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...