Hans,
I think your problem is that you don't use the variable which takes different
values in your if statement .... your "i" changes values and has really nothing
to do with your x variable (except the length part ....). Also all the other
variables need to be declared somehow - otherwise how can you store values in
them???
So your first code may be something like that:
t=c(1,2)
for(i in 1:length(t)){
if (i==1) t[i]=i+1 else t[i]=i
}
t[1] 2 2
and your second code:
a = c(1,2)
b=c(1,2)for(i in 1:2){if (i==1){a[i]=ib[i]=i-1} else{
a[i]=i+1b[i]=i}c<-list(a=a,b=b)}
> c$a[1] 1 3> c$b[1] 0 2
Also when you have only 2 possible values for "i" i don't think the second "if"
is necessary. I hope this helps a little, although my explanation is not
necessarily the best.
Monica
------------------------------ Message: 16Date: Tue, 4 Sep 2007 15:59:54
+0200From: Hans Ole ?rka <[EMAIL PROTECTED]>Subject: [R] For loop with if else
statementTo: "'[email protected]'"
<[email protected]>Message-ID:<[EMAIL PROTECTED]>Content-Type:
text/plain; charset="iso-8859-1" Hi,I try to make a simple for loop with a if
else statement (First example - Below) and extend it to a more complex loop
(Second example). However, my results #First example:x=c(1,2)t=for(i in
1:length(x)){if (x==1){a=x+1}elseif (x==2){a=x}} Returned from R:Warning
messages:1: the condition has length > 1 and only the first element will be
used in: if (x == 1) {2: the condition has length > 1 and only the first
element will be used in: if (x == 1) {> t[1] 2 3 However, the result i had
liked to get was t=c(2,2) i.e. using the first function (a=x+1) for x[1] and
(a=x) for x[2]. I can remove the Warnings by making: if (x[i]==1) etc. but this!
do not make the results any better. #Second example:x=c(1,2)t<-for(i in
1:length(x)){if (x==1){a=xb=x-1}elseif (x==2){a=x+1b=x}b<-list(a=a,b=b)}
Returned from R:Warning messages:1: the condition has length > 1 and only the
first element will be used in: if (x == 1) {2: the condition has length > 1 and
only the first element will be used in: if (x == 1) {> t$a[1] 1 2 $b[1] 0 1 The
result i like to get are $a =c(1,3) and $b=c(0,2) Probably there are couple of
things that I do wrong and I appreciate all help!
_________________________________________________________________
Discover the new Windows Vista
[[alternative HTML version deleted]]
______________________________________________
[email protected] 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.