# Add vectors of unequal length R without recycling

In R, 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 ‘a’ and ‘b’ have unequal (different) lengths

> a = c(10, 20, 30)

> b = c(1, 2, 3, 4, 5, 6, 7, 8, 9)

> a + b

their sum is computed by recycling values of the shorter vector ‘a’.

[1] 11 22 33 14 25 36 17 28 39

And I wondered, why the shorter vector ‘a’ 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?

Recycling may be useful, for example

without recycling you would get:

> a <- c(10, 20, 30)

> a + 1

[1] 11 20 30

which would be pretty inconvenient.

However, if some feature does not suit you, you can make your own function or code segment. For example,

> a <-c(10,11,12)

> b <-c(1,2,3,4,5,6,7,8,9)

```
```myadd<-function(x, y) {

if(length(x)!=length(y)) {

n <- min(length(x), length(y))

length(x) <- n

length(y) <- n

x[is.na(x)]<-0

y[is.na(y)]<-0

}

x+y

}

`> myadd(a,b)`

(Note that the recycling rule has to make a special case for when one

the argument has length zero – the output then has length zero as well.)