[R] Replace values according to conditions
Richard.Cotton at hsl.gov.uk
Richard.Cotton at hsl.gov.uk
Wed Apr 9 09:51:54 CEST 2008
> I have the following data called mydata in a data.frame
>
> Col1 Col2 Col3 Col4 Col5
> 1 2 4 6 7
> 8 8 7 3 5
> 4 4 5 6 7
>
> I want to replace the data according to the following conditions
>
> Condition 1 if data <= 3, replace with -1
> Condition 2 if data >=6, replace with 1
> Condition 3 if data = 4 or data =5, replace with 0
>
> So the expected output for the example, would be
> Col1 Col2 Col3 Col4 Col5
> -1 -1 0 1 1
> 1 1 1 -1 0
> 0 0 1 1 1
>...
> 1. I would like to know if there are better ways to achieve the expected
> output?
mydata[mydata<=3] = -1
mydata[mydata==4 | mydata==5] = 0
mydata[mydata>=6] = 1
See the Intro to R, section 2.7.
> 2. What are the symbols for OR and AND in R?
There are two versions: | and & that do elementwise logical comparisons on
vectors; and || and && that are quicker for scalar logical comparisons
(mostly used in 'if' statement conditions).
See the Intro to R, section 2.4 and 9.2.1.
Regards,
Richie.
Mathematical Sciences Unit
HSL
------------------------------------------------------------------------
ATTENTION:
This message contains privileged and confidential inform...{{dropped:20}}
More information about the R-help
mailing list