[R] Ifelse statement

Sarah Goslee sarah.goslee at gmail.com
Mon Jul 11 22:03:44 CEST 2011


Hi,

You've got several things going on here.

On Mon, Jul 11, 2011 at 3:39 PM, fre <fre_stamlid at hotmail.com> wrote:
> Hello everyone,
>
> I have a (small) issue. I already googled a lot, so I decided to use ifelse
> instead of if (){} else{}
>
> All the elements seem to work seperately, but combined in the ifelse
> statement, it doesn't seem to work.
>
> #The price function is a function which is normally distributed with only
> positive answers
> price<-function() {abs(rnorm(1,10,25))}
>
> #Before I use pieceprice in the ifelse, I need it to be defined
> pieceprice<-cbind()

This isn't true. You aren't passing pieceprice to your function, so
you don't need to define it first.

So you are creating an empty object pieceprice here.


> #Now I define a function with an ifelse statement. So if the binomial
> deviation returns one, I add a 'new' price() to the pieceprice vector else I
> repeat the last element of the pieceprice vector and add it to pieceprice.
> pricechange<-function()
> {ifelse(rbinom(1,1,2/3)==1,
> pieceprice<-cbind(pieceprice,price()),
> pieceprice<-cbind(pieceprice,pieceprice[1,length(pieceprice)]))}
>
> #But now if I try this (Even with rbinom(1,1,1), pieceprice remains NULL
> pricechange()
> pieceprice
>

Now you're doing some stuff in your function, and returning a value.

>> pricechange()
> [1] 79.20426

But you're not assigning your value to anything, so it's being printed
in the screen. Assigning it *within the function* by design and
default does not change anything in the outer environment.

>> pieceprice
> NULL

You didn't change pieceprice, so it hasn't changed.

pieceprice <- pricechange()

will run the function and assign its output to the object pieceprice,
which doesn't have to already exist.

>
> I hope someone has a clue what's wrong.
>
> Thanks a lot for your help!

Leaving aside the utility of functions that only ever return one
possible value, you would probably benefit from reading some
introductory material on writing functions.

Sarah

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



More information about the R-help mailing list