Reputation: 115
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 }
Upvotes: 0
Views: 884
Reputation: 5068
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
Upvotes: 1
Reputation: 93811
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()
Upvotes: 2