[R] Conditions in R (Help Post)
Jim Lemon
drj|m|emon @end|ng |rom gm@||@com
Tue Oct 22 23:38:01 CEST 2019
Hi Yeasmin,
I suspect that you didn't intend to have conditions like:
a<0 && b>0 && b<a)
I'm going to guess that you meant:
a < 0 && b > 0 && abs(b) < abs(a)
If this is the case, the following function seems to return the values
of phase that you want:
assign_phase<-function(x,y) {
phase<-c(1,2,7,8,3,4,6,5)
phase_index<-4 * (x > 0) + 2 * (y > 0) + (abs(x) < abs(y))
return(phase[phase_index+1])
}
Jim
On Wed, Oct 23, 2019 at 3:43 AM Yeasmin Alea <yeasmin.alea using gmail.com> wrote:
>
> Hello Team
> I would like to add a new column (for example-Phase) from the below data
> set based on the conditions
> YEAR DAY X Y Sig
> 1 1981 9 -0.213 1.08 1.10
> 2 1981 10 0.065 1.05 1.05
> *Conditions*
>
> D$Phase=sapply(D,function(a,b) {
> a <-D$X
> b<-D$Y
> if (a<0 && b<0 && b<a)
> {phase=1} else if (a<0 && b<0 && b>a)
> {phase=2} else if (a<0 && b>0 && b<a)
> {phase=7} else if (a<0 && b>0 && b>a)
> {phase=8} else if (a>0 && b<0 && b<a)
> {phase=3} else if (a>0 && b<0 && b>a)
> {phase=4} else if (a>0 && b>0 && b>a)
> {phase=6} else (a>0 && b>0 && b<a)
> {phase=5}
> })
>
> Can anyone help to fix the script to get a Phase column based on the
> conditions. The table will be like the below
> YEAR DAY X Y Sig Phase
> 1 1981 9 -0.213 1.08 1.10 phase=7
> 2 1981 10 0.065 1.05 1.05 phase=6
>
> Many thanks
> Alea
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list