Manuel K
Manuel K

Reputation: 67

How to loop a function in r?

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

Upvotes: 1

Views: 35

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102800

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))

Upvotes: 1

Related Questions