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}else
if (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=x
                b=x-1}else
        if (x==2){
                a=x+1
                b=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!

______________________________________________
R-help@stat.math.ethz.ch 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.

Reply via email to