How to combine functions in a plot in R
How to combine functions in a plot in R
This is my code so far:
Basically, I want x^2[0;10] & 6[11, infinity]
random <- function(x){
if (any(x <= 10 )) {
return (x**2)}
else if (any(x > 10 )){
return(6) }
}
Unfortunately, R uses only the first part of the function when I try to plot or integrate it.
Thanks for your help!
1 Answer
1
Your error is because of the use of the "any" function. any(x <= 10) will always be true as long as a single value in x is less than ten, e.g. it'll be true for [1, 2, 10, 15, 30]. Because of this, this function never reaches the second if statement.
What you actually want to do is map this function. First, remove the "any" calls in your function. Then pass in your function (labelled here as "random") into a map function. A map function is a dynamic function, one that takes in a function and a list of objects (in this case numbers) as its arguments. The map then applies the function to each element of said list.
E.g.
Mapping [1, 2, 3, 4] with x**2 returns [1, 4, 9, 16].
Mapping [1, 5, 15, 20] with random returns [1, 25, 6, 6]
There are several different mapping functions in R, so look here to pick which one is best for you. Some even include if statements which may save you time.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Comments
Post a Comment