Vector Addition in R

> # Let’s check how R treats addition of vectors
> a=c(1,2,3,4)
> a
[1] 1 2 3 4
> b=c(5,6,7,8)
> b
[1] 5 6 7 8
> #notice a and b both has same length
> length(a)
[1] 4
> length(b)
[1] 4
> #lets add a and b
> a+b
[1] 6 8 10 12
> length(a+b)
[1] 4
> #it did a simple addition where a[1] is added to b[1]
> #now lets make another vector
> c=(1)
> a+c
[1] 2 3 4 5

> #If the two vectors aren’t the same size, R will repeat the smaller sequence multiple
># times

> #test
> c/a
[1] 1.0000000 0.5000000 0.3333333 0.2500000
> c/b
[1] 0.2000000 0.1666667 0.1428571 0.1250000
> d=(2,9)
Error: unexpected ‘,’ in “d=(2,”
> d=c(2,9)
> a+d
[1] 3 11 5 13
> a/d
[1] 0.5000000 0.2222222 1.5000000 0.4444444
> c/d

Leave a Comment

Your email address will not be published. Required fields are marked *