[R] creating a function using for if

Sarah Goslee sarah.goslee at gmail.com
Mon Oct 22 18:15:16 CEST 2012


Then what about:

fun<-function(a,b,c,data) {
   ifelse(data > c, (a*(data-c)^0.5)+(b*(data-c)), 0)
}

 y=c(100,210,320,130,170,120,220,90,55,45)
 fun(10000,0.2,150,data=y)

>  fun(10000,0.2,150,data=y)
 [1]      0.00  77471.67 130418.05      0.00  44725.36      0.00  83680.00
 [8]      0.00      0.00      0.00

Sarah

On Mon, Oct 22, 2012 at 11:24 AM, Balqis <aehan3616 at gmail.com> wrote:
> thank you. yes I want to loop over the elements of the data. I want the
> output to be corresponded to the input by unchanging index. at the same
> time, the data that is more than c value should follow the
> function (a*(data-c)^0.5)+(b*(data-c), and the rest (same or less than c)
> should return a zero.  I tried adjusting the code (which is still in
> ridiculous form and need some comments);
>
> fun<-function(a,b,c,data)
> {
> N=rep(NA,length(data))
> for (i in 1:length(data)){
> if(data>c){
> N[i]<-(a*(data-c)^0.5)+(b*(data-c))}
> else
> {N[i]<-0}
> }
> return(N)}
>
> #try dummy
> y=c(100,210,320,130,170,120,220,90,55,45)
> try=fun(10000,0.2,150,data=y)
>
> On Mon, Oct 22, 2012 at 3:51 PM, Balqis <aehan3616 at gmail.com> wrote:
>
>> Hi all,
>>
>> I'm trying to create a function where it can process a vector and also
>> give a vector output accordingly
>> #input: a,b anc c are constants, data is the vector
>>
>> #set the function
>> fun<-function(a,b,c,data)
>> {
>> N=as.vector()
>> for (i in min(data):max(data)){
>> if(i>c){
>> N<-(a*(i-c)^0.5)+(b*(i-c))}
>> else
>> {N<-0}}
>> return(N)
>> }
>>
>> #try dummy
>> data=c(100,210,320,130,170,120,220,90,55,45)
>> try=fun(10000,0.2,150,data=data)
>>
>> what I get is:
>> Error in as.vector() : argument "x" is missing, with no default
>>
>> Please help, thanks!
>>

-- 
Sarah Goslee
http://www.functionaldiversity.org




More information about the R-help mailing list