for loop - Summation of max function with vector input in R? -
i want build function: f(a,b)=sum_{i=1 n}(max(a-b_i,0)) b=(b_1,b_2,...b_n). have done:
vec<-function(a,b){ z<-0 for(i in b){ ifelse(a > i,z <- z + (a-i), 0) } return(data.frame(z)) }
this code gives correct output scalar input of a. while using vector output answers not correct. example
> vec(c(-6,5),c(3,1,3)) gives -25 a=-6 , 8 a=5 respectively. > vec(-6,c(3,1,3)) gives 0. , correct answer.
please throw give idea how correct it.
when let a = c(-6,5)
, argument a > i
becomes (false, true)
. since contains true, vector passed z <- z + (a-i)
. note if use a=-6
in formula, output of -25
. suggest doing this:
vec<-function(a,b){ z<-0 for(i in b){ p <- ifelse(a > i,z <- z + (a-i), 0) } return(data.frame(p)) }
Comments
Post a Comment