How create a graphy with 3 functions defined by parts?

Hi,

I have this situation:

função_partes = function(x) {
ifelse (x < -1, -x, ifelse(x > 1, x, -(x^2)))
}

I wanna create a graphy (preferably ggplot) showing the resulting of the "função_partes".
The graphycs that i've been created dont respect de boundry of the function.

Can you helpe me?

Is this the kind of thing you are looking for?

library(ggplot2)
funcao_partes = function(x) {
  ifelse (x < -1, -x, ifelse(x > 1, x, -(x^2)))
}
DF <- data.frame(Xval = seq(-2, 2, 0.1), Yval = funcao_partes(seq(-2, 2, 0.1)))
ggplot(DF, aes(x = Xval, y = Yval)) + geom_line() + geom_point()

Created on 2020-10-05 by the reprex package (v0.3.0)

Yes!! Thanks a lot!!

But i dont wanna show the line with no results

You can drop geom_line entirely or graph three different lines as shown below.

library(ggplot2)
library(dplyr)
funcao_partes = function(x) {
  ifelse (x < -1, -x, ifelse(x > 1, x, -(x^2)))
}
DF <- data.frame(Xval = seq(-2, 2, 0.1), Yval = funcao_partes(seq(-2, 2, 0.1)))
ggplot(mapping = aes(x = Xval, y = Yval, group = 1)) + geom_point(data = DF) +
  geom_line(data = filter(DF, Xval >= -1, Xval <= 1)) +
  geom_line(data = filter(DF, Xval < -1)) +
  geom_line(data = filter(DF, Xval > 1))

Thanks!! Fantastic!!

FJCC, why do you put seq (-2, 2, 0.1) ? If I change 0.1 for 0, for example, the graphyc change.. can you help one more time?

seq makes sequences of numbers, the params are

seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)),
    length.out = NULL, along.with = NULL, ...)

(This information is available to you through the R help feature, where typing questionmark and the function name gives you a document to read)

?seq

changing the by parameter from 0.1 to 0 would mean that the sequence never advances from the start to the end, and R will reject this.

Thanks friend! It help me a lot!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.