简体   繁体   中英

Plotting piecewise functions in R

I'm trying to plot the piecewise function below using if statements, and I keep getting the

Error: unexpected '}' in "}"

message. All of my braces seem just fine to me, so I don't know where this is coming from. Any advice here would be appreciated. (Also, this is basically the first time I've done something like this in R, so please bear with me).

x.values = seq(-2, 2, by = 0.1)
n = length(x.values)
y.values = rep(0, n)
for (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 be done without a loop by taking advantage of the fact that R functions are usually vectorized.

For example:

library(tidyverse)
theme_set(theme_classic())

dat = data.frame(x=x.values)

In base R, you can do:

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

With tidyverse functions you can do:

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

Then, to plot:

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

在此处输入图片说明

When I ensure the newlines are in the right place, I don't get errors about unexpected symbols:

x.values = seq(-2, 2, by = 0.1)
n = length(x.values)
y.values = rep(0, n)
for (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 
}

However, what I do get is a complaint that y doesn't exist on the last line.

Since this is a homework assignment, I'll stop with this partial answer :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM