You want to display the value of a variable or expression.
Solution
If you simply enter the variable name or expression at the command prompt, R will print its value. Use the print function for generic printing of any object. Use the cat function for producing custom formatted output
Use the c(...) operator to construct a vector from given values.
Discussion
Vectors are a central component of R, not just another data structure. A vector can contain either numbers, strings, or logical values but not a mixture.
The c(...) operator can construct a vector from simple elements:
> c(1,1,2,3,5,8,13,21)
[1] 1 1 2 3 5 8 13 21
> c(1*pi, 2*pi, 3*pi, 4*pi)
[1] 3.141593 6.283185 9.424778 12.566371
> c("Everyone", "loves", "stats.")
[1] "Everyone" "loves" "stats."
> c(TRUE,TRUE,FALSE,TRUE)
[1] TRUE TRUE FALSE TRUE
If the arguments to c(...) are themselves vectors, it flattens them and combines them into one single vector:
> v1 <- c(1,2,3)
> v2 <- c(4,5,6)
> c(v1,v2)
[1] 1 2 3 4 5 6
Vectors cannot contain a mix of data types, such as numbers and strings. If you create a vector from mixed elements, R will try to accommodate you by converting one of them:
You want to calculate basic statistics: mean, median, standard deviation, variance, correlation, or covariance.
Solution
Use one of these functions as applies, assuming that x and y are vectors:
mean(x)
median(x)
sd(x)
var(x)
cor(x, y)
cov(x, y)
Discussion
When I first opened the documentation for R, I begin searching for material entitled “Procedures for Calculating Standard Deviation.” I figured that such an important topic would likely require a whole chapter.
It’s not that complicated.
Standard deviation and other basic statistics are calculated by simple functions. Ordinarily, the function argument is a vector of numbers and the function returns the calculated statistic:
> x <- c(0,1,1,2,3,5,8,13,21,34)
> mean(x)
[1] 8.8
> median(x)
[1] 4
> sd(x)
[1] 11.03328
> var(x)
[1] 121.7333
The sd function calculates the sample standard deviation, and var calculates the sample variance.
The cor and cov functions can calculate the correlation and covariance, respectively, between two vectors:
You want to compare two vectors or you want to compare an entire vector against a scalar.
Solution
The comparison operators (==, !=, <, >, <=, >=) can perform an element-by-element comparison of two vectors. They can also compare a vector’s element against a scalar. The result is a vector of logical values in which each value is the result of one element-wise comparison.
Discussion
R has two logical values, TRUE and FALSE. These are often called Boolean values in other programming languages.
The comparison operators compare two values and return TRUE or FALSE, depending upon the result of the comparison: