김수운태
김수운태

Reputation: 31

How do you express a equation or function as a graph(ggplot2) in R?

Working on a model to express the profit derived from call options.

With the price of the stock(St) should have a range of 0-200 and the actual price of the event(K) set as 100.

The equation for the actual profit goes as max(St-K,0)

I want to express a graph with the x axis as St and y axis as the results derived from the equation max(St-K,0)

K <- 100
St <- c(0:200)
Ap <- c(max(St-K,0))

ggplot(mapping = aes(x=St, y=Ap)) + geom_line()

The code above shows a straight line, however, I need a graph where the line stays dormant until 100 on the x axis, then the profit should rise as in accordance with the equation.

Like this enter image description here

What is required to achieve a graph like this? Do I need to functionalize the equation and use lapply or sapply?

Upvotes: 0

Views: 111

Answers (1)

duckmayr
duckmayr

Reputation: 16910

The function you want is pmax(), or element-wise max, rather than max(), which gives you the maximum of all the elements. That's why it's just a straight line; max() outputs a single value.

So,

library(ggplot2)
K <- 100
St <- c(0:200)
Ap <- c(pmax(St-K,0))

ggplot(mapping = aes(x=St, y=Ap)) + geom_line()

enter image description here

Upvotes: 1

Related Questions