[R] Add vectors of unequal length without recycling?

William Dunlap wdunlap at tibco.com
Wed Dec 13 17:34:42 CET 2017


Without recycling you would get:
    u <- c(10, 20, 30)
    u + 1
    #[1] 11 20 30
which would be pretty inconvenient.

(Note that the recycling rule has to make a special case for when one
argument has length zero - the output then has length zero as well.)


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Tue, Dec 12, 2017 at 9:41 PM, Maingo via R-help <r-help at r-project.org>
wrote:

> I'm a newbie for R lang. And I recently came across the "Recycling Rule"
> when adding two vectors of unequal length.
>
> I learned from this tutor [ http://www.r-tutor.com/r-
> introduction/vector/vector-arithmetics ] that:
>
> """"""
>
> If two vectors are of unequal length, the shorter one will be recycled in
> order to match the longer vector. For example, the following vectors u and
> v have different lengths, and their sum is computed by recycling values of
> the shorter vector u.
>
> > u = c(10, 20, 30)
>
> > v = c(1, 2, 3, 4, 5, 6, 7, 8, 9)
>
> > u + v
>
> [1] 11 22 33 14 25 36 17 28 39
>
> """"""
>
> And I wondered, why the shorter vecter u should be recycled? Why not just
> leave the extra values(4,5,6,7,8,9) in the longer vector untouched by
> default?
>
> Otherwise is it better to have another function that could add vectors
> without recycling? Right now the recycling feature bugs me a lot.
>
> Sent with [ProtonMail](https://protonmail.com) Secure Email.
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list