I am trying to represent the following density function with R:
$$
f(x)=
\left\{
\begin{array}{lcc}
0 & si & x < 0 \\
\\ 2-2\cdot x & si & 0 \leq x \leq 1 \\
\\ 0 & si & x > 1
\end{array}
\right.
$$
Which looks like this:
The code in R:
x = seq(0, 1, length = 1000) #Secuencia de 1.000 puntos entre 0 y 1
plot(
x, 2-2*x, #f(x) entre 0 y 1
type = "l", #Representación de tipo línea
main = "Función de densidad",
ylab = "f(x)",
xlab = "x",
lwd = 1, #Grosor
xlim = c(-0.5, 1.5), #Ampliación de los ejes
ylim = c(-0.5, 2.5)
)
lines(c(-1, 0), c(0 ,0), lwd = 1) #f(x) para valores menores de 0
lines(c(1, 0), c(2, 0), lwd = 1) #f(x) para valores mayores de 1
points(0, 0, pch = 1) #Puntos de transición
points(0, 2, pch = 19)
points(1, 0, pch = 19)
text(0, 0, labels = "(0, 0)", pos = 1)
text(0, 2, labels = "(0, 2)", pos = 3)
text(1, 0, labels = "(1, 0)", pos = 1)
However, I get the following:
Namely:
lines(c(1, 0), c(2, 0), lwd = 1) #f(x) para valores mayores de 1
Represent a line between (0, 0) and (1, 2) instead of between (1, 0) and (2, 0).
Why could this be happening?
A greeting and Thanks forward.
The problem is that it
lines
expects one vector for the values ofx
and another for the ofy
and what I understand you are trying to do is pass points A and B directly, you should modify this:by
The first vector is the values of
x
that goes from 1 to 2 and the next is they
one that is always 0.