0

I have a function

g(h) = 2h for -20 <= h <= 20 and 1 otherwise.

How can I plot this using R?

Very new to R so thanks for any guidance

1 Answers1

2

For a basic plot, it doesn't much matter whether your function is piecewise or not. Make it a function, then plot it. Pick your favorite method from the How to plot a function? FAQ. I show two possibilities below. If you want to avoid the vertical line connecting the pieces, then you'll need to plot each piece independently.

foo = function(x) {
  ifelse(-20 <= x & x <= 20, 2*x, 1)
}

## base plot:
curve(foo, from = -25, to = 25)

## with ggplot
library(ggplot2)
ggplot(data.frame(x = c(-25, 25)), aes(x = x)) +
  stat_function(fun = foo)

enter image description here

enter image description here

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Hi, quick question. If I had a third condition in function such as g(h) = 2h for -20 <= h <= 20, 0 for h < -20, and 1 otherwise. How can I add that to the ifelse statement ? –  Nov 30 '20 at 06:36
  • Nesting them, `ifelse(h < -20, 0, ifelse(h < 20, 2 * h, 1))`. – Gregor Thomas Nov 30 '20 at 06:37