[R] For loop with if else statement
Duncan Murdoch
murdoch at stats.uwo.ca
Tue Sep 4 16:51:06 CEST 2007
On 9/4/2007 9:59 AM, Hans Ole Ørka wrote:
> 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.
x is a vector of length 2. Using a = x + 1 means that the entire vector
a will be replaced by the entire vector x. You need to index each entry
each time you use it, i.e.
if (x[i] == 1) a[i] <- x[i] + 1
else if (x[i] ==2]) a[i] <- x[i]
or more simply, throw away the loop, and use the ifelse function:
a <- ifelse( x == 1, x + 1,
ifelse( x == 2, x,
NA) )
(where I've used NA for the case where x is neither 1 nor 2.)
Duncan Murdoch
>
> #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 at 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.
More information about the R-help
mailing list