[R] creating a function using for if
Sarah Goslee
sarah.goslee at gmail.com
Mon Oct 22 17:01:51 CEST 2012
N=as.vector()
This doesn't mean anything in R: you can read the help using
?as.vector
to see what the required arguments are.
Do you want to loop over the elements of data? That's not what your
loop is doing. Instead it is looping over each element of the sequence
from the min to the max *value* of data. It isn't actually doing
anything with data (which btw is a bad thing to call your data, since
it's also the name of a function, and really not very descriptive),
just extracting the min and max and ignoring the actual values.
Your loop is also only returning a single value. Presumably what you want is
N <- rep(NA, lengthofdesiredresult) # I'm not sure what that is
and to actually index N within the loop, ie
N[i] <- somevalue
You did a good job of providing fake data, thank you. But you also
need to tell us what your expected result is, since it isn't clear
from your code which parts are misunderstandings and which are
intentional.
Sarah
On Mon, Oct 22, 2012 at 10:51 AM, 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