Reputation: 87
I am trying to write a function based on this formula.
(x − x0)^ r+ = { (x-x0)^r if x>x0
0 otherwise
what I understood from above is;
y= (x-x0)^r unless x<= x0
so for each element of, identify if greater and x0 if so return y that equals the formula.
tp <- function(x,x0,r) {
y<-list()
if (x[i] >x0) {
for (i in seq_along(x)) {
y<- append((x[i]-x0)^r)
} else {
y <- append(0)
}
}
return(y)
}
I have tried doing this but I couldn't make it work. Could anyone advise me if I understood the formula right and if so what is the correct way to coed it.
Upvotes: 1
Views: 158
Reputation: 459
An alternative to the if else statement is to use boolean logic, which I like. But both will work.
tp <- function(x, x0, r) {
# ifelse(x > x0, (x - x0)^r, 0)
(x > x0)*(x - x0)^r
}
x0 <- 2
tp(-2:5, x0, r = 2)
#> [1] 0 0 0 0 0 1 4 9
Upvotes: 4
Reputation: 160607
Issues with your function:
append
needs a list or vector to which the values are appended, so you need to do y <- append(y, ...)
;for
expression should be before (outside) the first (x[i] > x0
) conditional; andy <- numeric(0)
makes more sense to me than list
. There are certainly times when a list makes sense, but this is not one of them (in my perspective). Again, not wrong, but later processing will likely be more efficient as a vector.Perhaps something like:
tp <- function(x,x0,r) {
y <- numeric(0)
for (i in seq_along(x)) {
if (x[i] > x0) {
y <- append(y, (x[i]-x0)^r)
} else {
y <- append(y, 0)
}
}
return(y)
}
In R, it is almost always preferred to use vectorized operations instead of for
loops. In this case, I think you can easily use the vectorized function that RuiBarradas provided (which is the preferred method for writing this kind of function).
Upvotes: 1
Reputation: 76575
Use ifelse
.
tp <- function(x, x0, r) {
ifelse(x > x0, (x - x0)^r, 0)
}
x0 <- 2
tp(-2:5, x0, r = 2)
#> [1] 0 0 0 0 0 1 4 9
Created on 2022-12-01 with reprex v2.0.2
Upvotes: 2