1
Example: 
a <- function(b,c,d,e,f){ 
if(f == 1){
  Value1 <- b * c * d * e
  return(Value1)
}else if(f == 2){
  Value2 <- b * c * d
  return(Value2) 
}else{
  Value3 <- 0 
}
}

Assume I would like to analyze the relationship between Value2 and d for d = seq(0,2,0.05) if b,c,e are fixed and I can't change the function. So I would like to plot a graph with Value2 on the y-axis and d on the x-axis. What I tried: Construct a vector and combine them with seq(0,2,0.05)

ValueChange <- c() 

for( i in seq(0,2,0.05)){
  ValueChange <- a(10,2,i,5,2)
}
ValueChange 

Unfortunately, that didn't work

0

1 Answer 1

1

Maybe your for loop should be like below

for( i in seq(0,2,0.05)){
  ValueChange <- c(ValueChange,a(10,2,i,5,2))
}

where the newly generated value a(10,2,i,5,2) will be updated and appended to ValueChange


Or a more efficient way via sapply

ValueChange <- sapply(seq(0,2,0.05),function(i) a(10,2,i,5,2))
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't that an O(n^2) way of creating the vector?
@JohnColeman I know it is inefficient. An efficient way might be sapply. I just want to show OP what happened in the for loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.