[R] Odp: in continuation with the earlier R puzzle

Petr PIKAL petr.pikal at precheza.cz
Tue Jul 13 13:01:09 CEST 2010


Hi

r-help-bounces at r-project.org napsal dne 12.07.2010 16:09:30:

> When I just run a for loop it works. But if I am going to run a for loop
> every time for large vectors I might as well use C or any other 
language.
> The reason R is powerful is becasue it can handle large vectors without 
each
> element being manipulated? Please let me know where I am wrong.
> 
> for(i in 1:length(news1o)){
> + if(news1o[i]>s2o[i])
> + s[i]<-1
> + else
> + s[i]<--1
> + }

Think in R not in C. Why using loops when you can use whole object 
directly. It is like drinking beer from snifters. It is possible but using 
pints is preferable and more convenient.

news1o>s2o

gives you a logical vector the same length

and you can use it directly for further selection or computation. You can 
consider FALSE as 0 and TRUE as 1 and use it as numeric vector
so

x<-runif(10)
y<-runif(10)

c(-1,1)[(x>y)+1]

selects -1 when FALSE and 1 when TRUE.

or you can use it in mathematical operation directly

(x>y)*2-1

Regards
Petr

> 
> -- 
> 'Raghu'
> 
>    [[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