[R] Help with for loop

Erik Iverson eiverson at NMDP.ORG
Mon Sep 14 20:59:53 CEST 2009


It is difficult to know what you're trying to do here, I think.  Is this it? You almost surely don't need a for loop to accomplish your task, and should make use of the pre-existing vectorized functions provided to you. 

a <- c(4, 5, 1, 7, 8, 12, 39)
b <- c(3, 7, 8, 4, 7, 25, 78)
d <- a - b

which(d > 0)

Erik 

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Edward Chen
Sent: Monday, September 14, 2009 1:50 PM
To: r-help at r-project.org
Subject: [R] Help with for loop

I have a code:
*a = c(4,5,1,7,8,12,39)
b = c(3,7,8,4,7,25,78)
d =a-b
for(i in 1:length(d)){
if(d[i]>0){x = list(d[i])
print(x)}
else{y = list(d[i])
print(y)}}

the results are:

[[1]]
[1] 1

[[1]]
[1] -2

[[1]]
[1] -7

[[1]]
[1] 3

[[1]]
[1] 1

[[1]]
[1] -13

[[1]]
[1] -39


which will tell me what d is. but is it possible to output the order in
which the difference is in the vector d?
for example I would want to see x = 1,3,1 and they are from d[1], d[4],
d[5].
This is just a crude example I thought of to help me do something more
complicated.

Thank you very much!
*
-- 
Edward Chen
Email: edchen51 at gmail.com
Cell Phone: 510-371-4717

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