0
votes

I want to plot a self-defined function in R using two vectors and an unknown variable. I thought about something like this:

# Define parameters
b<-c(1.70,4.70,7.60)
w<-c(0.38,0.44,0.50)

# Define function
k<-function(x){0.07*(w*(1-(x/-33)^(1/b)))^4}

# Plot
plot(k)

The goal is to plot the function, getting three lines. One line should contain the first pair of the b-vector/w-vector, the second line should contain the second pair and the third line should contain the last pair of the vectors. When I compile the code I get an error message:

1: In (x/-33)^(1/b) : longer object length is not a multiple of shorter object length 2: In w * (1 - (x/-33)^(1/b)) : longer object length is not a multiple of shorter object length

My idea was, that R wants to combine all the values from each vector with each other, which leads to the error message. Is there a way around the error?

2
Not directly related to the warning message, but (x/-33)^(1/b) is going to give you NaN for x > 0 and your values of b. Since plot.function plots values for x in [0, 1] by default, you're not going to see anything on your plot. - Weihuang Wong

2 Answers

0
votes

The problem here is that plot needs a function that returns one value and not a vector.

One workaround would be to loop over your b and w values one by one and redefine your k function as you go. I've also changed your k function as it wasn't defined for the default parameters.

k <- function(b, w) {
  function(x){b*x+w}
}

plot2 <- function(k, b, w) {

  plot(k(b[1], w[1]))  
  for (i in 2:length(b)) {
    foo <- k(b[i], w[i])
    curve(foo, add = TRUE)
  }
}

plot2(k, b, w)
0
votes

If I understand you correctly this should give you the desired result.

b<-c(1.70,4.70,7.60)
w<-c(0.38,0.44,0.50)

curve((0.07*w[1])*((1-(x/(-33))^1/b[1])^4), from=0, to=20, type = 'l')

for(i in 2:length(b))
{
  curve((0.07*w[i])*((1-(x/(-33))^1/b[i])^4), from=0, to=20, add = TRUE)
}