Plotting piecewise functions in R -


i'm trying plot piecewise function below using if statements, , keep getting the

error: unexpected '}' in "}" 

message. of braces seem fine me, don't know coming from. advice here appreciated. (also, first time i've done in r, please bear me).

x.values = seq(-2, 2, = 0.1) n = length(x.values) y.values = rep(0, n) (i in 1:n) { x = x.values[i] if (x <= 0) {     y.values = -x^3 } else if (x <= 1) {     y.values = x^2 } else {     y.values = sqrt(x) }   y.values[i] = y } 

this can done without loop taking advantage of fact r functions vectorized.

for example:

library(tidyverse) theme_set(theme_classic())  dat = data.frame(x=x.values) 

in base r, can do:

dat$y = with(dat, ifelse(x <= 0, -x^3, ifelse(x<=1, x^2, sqrt(x)))) 

with tidyverse functions can do:

dat = dat %>%    mutate(y = case_when(x <= 0 ~ -x^3,                        x <= 1 ~ x^2,                        true ~ sqrt(x))) 

then, plot:

ggplot(dat, aes(x,y)) + geom_line() + geom_point() 

enter image description here


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -