# [R] functions applied to two vectors

Tony Plate tplate at acm.org
Wed Oct 24 05:38:50 CEST 2007

> a <- c(2, 3, 7, 5)
> b <- c(4, 7, 8, 9)
> mapply(seq, a, b)
[[1]]
[1] 2 3 4

[[2]]
[1] 3 4 5 6 7

[[3]]
[1] 7 8

[[4]]
[1] 5 6 7 8 9

> mapply(sum, a, b)
[1]  6 10 15 14
>

hope this helps,

Tony Plate

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
>
> Thank you,
> Anuta
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help