# Re: [R] strange behavior of my function

From: ronggui <ronggui.huang_at_gmail.com>
Date: Wed, 02 Apr 2008 00:02:53 +0800

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
> 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.html

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