A vector in R is like a column in Excel or a column in a database table.
By using the following command, I am adding values to cells in a column,
X = c(1,2,3)
Note:
I like to think in this way although it is not exactly true.
But it is easier to understand R vector if you are coming with a background from a database designer or an Excel user.
Aggregates
sum(X) is for calculating the total
mean(X) is for calculating the mean.
Here is a comparison of some aggregate functions available in Oracle database and what are their equivalent in R:
- SUM -> sum
- AVG – mean
- MAX -> max
- MIN->min
- COUNT-> length
- MEDIAN -> median
Order By
Here is a good example: Operations on vectors
> a = c(2,4,6,3,1,5) > b = sort(a) > c = sort(a,decreasing = TRUE) > a [1] 2 4 6 3 1 5 > b [1] 1 2 3 4 5 6 > c [1] 6 5 4 3 2 1
This is similar to issue an Order by clause.
Expression / mass update
Once you have the data in a vector, you can apply operations to every element in the vector using a single command:
> a <- c(1,2,3,4) > a [1] 1 2 3 4 > a + 5 [1] 6 7 8 9 > a - 10 [1] -9 -8 -7 -6 > a*4 [1] 4 8 12 16 > a/5 [1] 0.2 0.4 0.6 0.8
See Also: Basic Operations
Expression on more than one columns
> a=c(1,2,3) > b=c(10,20,30) > c=a+b > c [1] 11 22 33 >