-
3
pages
-
English
-
Documents
Description
R Tutorial 2Econ 5201. VectorsIn R, a variable can hold a vector of numbers. (You can also define matrices and arrays, as we'll see later on.) This is very handy because we can do a set of operations simultaneously on a large set of numbers. An easy way to construct a vector is to use the "c" command. This "concatenates" numbers into a vector:> x<- c(1,3,5,10)This defines a vector (1,3,5,10) and stores the entire vector in x. If you just type "x" at the prompt, you will see the entire vector:> x[1] 1 3 5 10Many arithmetic operations work element-by-element on vectors. For example:> x[1] 1 3 5 10> x+1[1] 2 4 6 11> 3*x[1] 3 9 15 30Also some functions work element-by-element on vectors:> exp(x)[1] 2.718282 20.085537 148.413159 22026.465795> log(x)[1] 0.000000 1.098612 1.609438 2.302585> sin(x)[1] 0.8414710 0.1411200 -0.9589243 -0.5440211Some functions in R work directly on a vector to return a scalar. For example:> sum(x)[1] 19> mean(x)[1] 4.75> sd(x)[1] 3.86221These calculate the sum of the elements in x, the mean (average) of the elements, and the (sample) standard deviation.Another useful type of calculation involves logical vectors. A logical vector is a vector where each element can be either "TRUE" or "FALSE." Logical vectors can be constructed using the concatenation function:> lv1 <- c(FALSE, TRUE, FALSE, TRUE)> lv1[1] FALSE TRUE FALSE TRUEor by applying a logical test to a vector, for ...
-
Publié par
-
Langue
English