[tech-spec] Re: loop return vector

  • From: Dirk Eddelbuettel <edd@xxxxxxxxxx>
  • To: tech-spec@xxxxxxxxxxxxx
  • Date: Sun, 27 Feb 2005 17:19:24 -0600

On 27 February 2005 at 12:44, James Sogi wrote:
| 
| Kudos to Tim. Good stuff.

Yup. Nice work. We could do with more of that on here ...
 
| Requesting help on ?"for" loop question (R 2.0 on XP), please.
| 
| for(i in 1:5) a <-  (i > 2)
|  > a
| [1] TRUE
|  > print(a)
| [1] TRUE
| 
| #how do I get it to return entire vector, not just 1? What am I missing 
| here?

You are assigning to a scalar, so it becomes a scalar. Alternatives:

i)   Vectorised assignmentL

> i <- 1:5
> a <- (i>2)
> a
[1] FALSE FALSE  TRUE  TRUE  TRUE


ii)  Assign to vector elements inside the loop, but note that you need to
*have* a suitable a before you can assign to a[i]:

> rm(a)
> a <- vector(length=5, mode="integer")
> for (i in 1:5) a[i] <- (i>2)
> a
[1] 0 0 1 1 1
> rm(a)
> a <- vector(length=5, mode="logical")
> for (i in 1:5) a[i] <- (i>2)
> a
[1] FALSE FALSE  TRUE  TRUE  TRUE

Hth, Dirk                                         


-- 
Better to have an approximate answer to the right question than a precise 
answer to the wrong question.  --  John Tukey as quoted by John Chambers

Other related posts: