[R] Add vectors of unequal length without recycling?

William Michels wjm1 at caa.columbia.edu
Wed Dec 13 19:17:51 CET 2017


Maingo,

See previous discussion below on rbind.na() and cbind.na() scripts:

https://stat.ethz.ch/pipermail/r-help/2016-December/443790.html

You might consider binding first then adding orthogonally.
So rbind.na() then colSums(), OR cbind.na() then rowSums().

Best of luck,

W Michels, Ph.D.



On Wed, Dec 13, 2017 at 8:34 AM, William Dunlap via R-help
<r-help at r-project.org> wrote:
> 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]]
>
> ______________________________________________
> 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.



More information about the R-help mailing list