Greetings R-users, 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 I have thought of using replace with each conditions, for example I tried the following myrep <- replace(mydata, mydat <= 3, -1 ) #Condition 1 I would have to repeat the function replace for each of the conditions to get the expected output. My questions are: 1. I would like to know if there are better ways to achieve the expected output? 2. What are the symbols for OR and AND in R? Thanks for any feedback -- Suhaila Zainudin [[alternative HTML version deleted]]
Richard.Cotton at hsl.gov.uk
2008-Apr-09 07:51 UTC
[R] Replace values according to conditions
> 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}}