[R] R question

Peter Malewski p.malewski at tu-bs.de
Thu Dec 16 21:19:57 CET 1999


Dear Faheem
Faheem Mitha wrote:

> I have the following question, which is elementary but I am unable to
> answer.
> In a for(i=10) loop, I am trying to represent the 10 1-dimensional vectors
> l1, l2,... l10 by some expression that will run through these values.
> ie. soppose I want to add l1 + ... + l10
> I could go
>
> x <- 0
> for(i in 1:10){ x <- x+ l(i)}

"()" indictes that a function is called.  You can use a expression like
(get(paste( ... ))

> Vec1 <- 1:10
> Vec1 <- 1:10
> Vec2 <- 1:10
> Vec3 <- 1:10
>  x <- 2
> for(i in 1:3) print(x + get(paste("Vec",i,sep="")))
 [1]  3  4  5  6  7  8  9 10 11 12
 [1]  3  4  5  6  7  8  9 10 11 12
 [1]  3  4  5  6  7  8  9 10 11 12


A better way might be a Data.frame / matrix representation:


> xx <- data.frame(Vec1,Vec2,Vec3)
> xx+x
   Vec1 Vec2 Vec3
1     3    3    3
2     4    4    4
3     5    5    5
4     6    6    6
5     7    7    7
6     8    8    8
7     9    9    9
8    10   10   10
9    11   11   11
10   12   12   12



> This should return x to be the sum of the 10 li's for i from 1 to 10
> except of course I'm doing something more complicated.
> But l(i) of course does not serve to represent l1 etc? What should I do?

??? Perhaps this includes a useful idea:

> x + apply(xx , 2 , sum)
Vec1 Vec2 Vec3
  57   57   57

or:

> apply(xx , 2 , function( yy )x + sum(yy))
Vec1 Vec2 Vec3
  57   57   57


Hope this answer will help a bit
Peter


>
>
>                                     Faheem Mitha,
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

--
** To YOU I'm an atheist; to God, I'm the Loyal Opposition. Woody Allen **
P.Malewski                                      Tel.: 0531 500965
Maschplatz 8                                    Email: P.Malewski at tu-bs.de
************************38114 Braunschweig********************************



-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list