[R] functions applied to two vectors

Rolf Turner r.turner at auckland.ac.nz
Wed Oct 24 05:28:36 CEST 2007


On 24/10/2007, at 4:15 PM, Anya Okhmatovskaia wrote:

> Hi,
>
> I am very new to R, so I apologize if I have missed some trivial  
> thing in
> the manuals/archives. I am trying to get rid of for loops in my  
> code and
> replace them with R vector magic (with no success).
>
> Let's say I have 2 vectors of the same length:
> a <- c(2, 3, 7, 5)
> b <- c(4, 7, 8, 9)
>
> What I'd like to do is to generate a list(?) of 4 sequences using a 
> [i] as a
> start indices, and b[i] as end indices:
> 2,3,4
> 3,4,5,6,7
> 7,8
> 5,6,7,8,9
>
> My first guess: "a:b", of course, does not work - only one sequence  
> gets
> generated using the first values from both vectors, plus a warning.  
> Is there
> a special syntax I can use to make ":" treat its operands as vectors?
> More generally, is there a standard way to apply some arbitrary  
> functions to
> two or more vectors in an element-by-element fashion? For instance,  
> sum(a,b)
> will sum all values in both vectors; how can I make it produce a  
> vector of
> pairwise sums instead?

Cute question!  The first idea that pops into my head is

	apply(cbind(a,b),1,function(x){x[1]:x[2]})

This works --- but there may be better ideas.

			cheers,

				Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}



More information about the R-help mailing list