![]() |
Introduction
To R |
> x <- 1:10 > x + 2 [1] 3 4 5 6 7 8 9 10 11 12 > x * 2 [1] 2 4 6 8 10 12 14 16 18 20 > sqrt(x) [1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751 2.828427 [9] 3.000000 3.162278If you operate on two vectors, the calculations are also done one element at a time:
> x <- 1:10 > y <- 21:30 > x+y [1] 22 24 26 28 30 32 34 36 38 40But what if the vectors are different lengths? In this case, R will always repeat the shorter vector until it is long enough:
> x <- 1:10 > y <- c(1,2) > x+y [1] 2 4 4 6 6 8 8 10 10 12Here R has repeated y five times, and added that to x, like this:
x : 1 2 3 4 5 6 7 8 9 10 y : 1 2 1 2 1 2 1 2 1 2 (repeated) ----------------------------------- x+y : 2 4 4 6 6 8 8 10 10 12However, if the length of the longer vector isn't an integer multiple of the length of the shorter vector, R will warn you:
> x <- 1:10 > y <- c(1,2,1) > x + y [1] 2 4 4 5 7 7 8 10 10 11 Warning message: longer object length is not a multiple of shorter object length in: x + y