[R] R: Replace values according to conditions

Guazzetti Stefano Stefano.Guazzetti at ausl.re.it
Wed Apr 9 11:04:51 CEST 2008


A short way (not necessairly the best way), using the coercion from
logical to numeric, could be:

(mydata<-as.data.frame(matrix(sample(1:9, 12, repl=T), ncol=4)))

 -1*(mydata <=3) + (mydata >=6)

For the second question start here:
 
help(Logic, package="base")  


Stefano

-----Messaggio originale-----
Da: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org]Per conto di Suhaila Zainudin
Inviato: mercoledì 9 aprile 2008 9.32
A: r-help at r-project.org
Oggetto: [R] Replace values according to conditions


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]]

______________________________________________
R-help at r-project.org mailing list
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