# Re: [R] strange behavior of my function

From: <Bill.Venables_at_csiro.au>
Date: Wed, 02 Apr 2008 15:24:16 +1000

There are simpler looking ways of doing this. Here are two

convert.to.trinom3 <- function(data, z1, z2)

ifelse(data < z1, 0, ifelse(data < z2, 1, 2))

convert.to.trinom3 <- function(data, z1, z2)

cut(data, c(-Inf, z1, z2, Inf), labels = FALSE) - 1

The second neatly generalizes to the case of more than three bins.

Bill Venables
CSIRO Laboratories
PO Box 120, Cleveland, 4163
AUSTRALIA

```Office Phone (email preferred): +61 7 3826 7251
Fax (if absolutely necessary):  +61 7 3826 7304
Mobile:                         +61 4 8819 4402
Home Phone:                     +61 7 3286 7700
```
mailto:Bill.Venables_at_csiro.au
http://www.cmis.csiro.au/bill.venables/

You should write the function in this way, I think.

convert.to.trinom3=function(data, z1, z2){

ans <- data

```   ans[data<z1]=0
ans[z1<=data & data<z2]=1
ans[data>=z2]=2
```

ans
}

On Tue, Apr 1, 2008 at 11:54 PM, Kyeongmi Cheon <katie.cheon_at_gmail.com> wrote:
> Hello,
> I wrote a program to convert normal distribution to trinomial
> distribution (three levels=0,1,2). But the first function I wrote
> (convert.to.trinom1) converts everything to 2. When I changed it
> slightly (convert.to.trinom2), it works correctly (ie. converts to
> 0,1, or 2). I cannot figure out why it happens. I even restarted R
and
> tried again and the same thing happened over and over. I use R 2.6.0
> in Windows Vista. Can anyone help me with this? Thank you.
> Kyeongmi
>
>
>
> norm1=rnorm(20)
> norm1
>
> z1=-1.2212272
> z2=-0.6744898
> convert.to.trinom1=function(data, z1, z2){
> data[data<z1]=0
> data[z1<=data & data<z2]=1
> data[data>=z2]=2
> data
> }
> trinom1=convert.to.trinom1(norm1,z1, z2)
> trinom1
>
> convert.to.trinom2=function(data, z1, z2){
> data[data>=z2]=2
> data[data<z1]=0
> data[z1<=data & data<z2]=1
> data
> }
> trinom2=convert.to.trinom2(norm1,z1, z2)
> trinom2
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

```--
HUANG Ronggui, Wincent

Bachelor of Social Work, Fudan University, China

Master of sociology, Fudan University, China

Ph.D. Candidate, CityU of HK,
http://www.cityu.edu.hk/sa/psa_web2006/students/rdegree/huangronggui.htm
l

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help