[R] Replace values according to conditions

Hans-Joerg Bibiko bibiko at eva.mpg.de
Wed Apr 9 10:46:14 CEST 2008


On 9 Apr 2008, at 09:51, Richard.Cotton at hsl.gov.uk wrote:
>> 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
> mydata[mydata<=3] = -1
> mydata[mydata==4 | mydata==5] = 0
> mydata[mydata>=6] = 1

An other more restrictive approach would be IF the matrix' cells are  
positive integer values in a definite range you can set up a vector  
containing the results of the conditions for each index representing  
the matrix cell content:

cond <- c(-1, -1, -1, 0, 0, 1, 1, 1)


and invoke:

apply(mydata, 2, function(x) cond[x])

or even shorter:

apply(mydata, 2, function(x) c(-1, -1, -1, 0, 0, 1, 1, 1)[x])

=======

If you haven't got a definite range and only a few conditions this is  
also possible:

apply( mydata, 2, function(x) ifelse(x<=3,-1, ifelse(x>=6,1,  
ifelse(x==4|x==5,0,x))) )


Kind regards,

--Hans



More information about the R-help mailing list