R Language Quick Reference Guide II

The article is about the R Language Quick Reference Guide. This Quick Reference will help you to learn about creating vectors, matrices, data frames, lists, and factors. You will also learn about setting properties of different data types in R Language.

R Language Quick Reference Guide

R Language Quick Reference Guide

R language Quick Reference Guide is about learning R Programming with a short description of the widely used commands. It will help the learner and intermediate user of the R Programming Language to get help with different functions quickly. This Quick Reference is classified into different groups. Let us start with R Language Quick Reference Guide – II.

This R Language Quick Reference Guide contains R commands about creating vectors, matrices, lists, data frames, arrays, and factors. It also discusses setting the different properties related to R language data types.

Creating Vectors in R Language

The creation of a row or column vector in the R Language is very important. One can easily create a vector of numbers, characters/ strings, complex numbers, and logical values, and can concatenate the elements. The following are different commands for creating Vectors in R

R commandShort Description
c(a1, a2, …, an)Concatenates all $n$ elements to a vector
logical(n)Creates a logical vector of length $n$ (containing false)
numeric(n)Creates a numeric vector of length $n$ (containing zeros)
character(n)Creates a character vector of length $n$ (containing an empty string)
complex(n)Creates a complex vector of length $n$ (containing zeros)

Creating Lists in R Language

Creating Lists in R is important as it can store different types of data and even lists. A vector can also be used to create a list of $k$ elements. The following are ways for creating lists in R language.

R CommandShort Description
list(e1, e2, … ek)Combines all $k$ elements as a list
vector(k, “list”)Creates a list of length $k$ (the elements are all NULL)

Creating Matrices in R Language

Two-dimensional data can be created using the matrix command in R.

R CommandShort Description
matrix(x, nr = r, nc = c)Creates a matrix from $x$ (column as major order)
matrix(x, nr = r, nc = c)Creates a matrix from $x$ (row as major order)

Creating Factors in R Language

To create categorical variables, R has a concept of factors as variables. All factors have levels that may have ordered factors.

R CommandShort Description
factor(x)Creates a factor from the values of variable $x$
factor(x, levels = 1)Creates a factor with the given level set from the values of the variable $x$
ordered(x)Creates an ordered factor with the given level set from the values of the variable $x$
levels(x)Gives the levels of a factor or ordered factor
levels(x) = vSet or reset the levels of a factor or ordered factor

Creating a Data Frame in R Language

A data frame is a tabular data format used for statistical data analysis. The format of the data is like data entered in spreadsheets for data analysis.

R CommandShort Description
data.frame(n1=x1, n2=x2, ….)Creates a data frame

R Language Data Type Properties

Every data object has different properties. These properties can be used to find out the number of rows in a vector or matrix, the number of columns, names of rows and columns of a matrix or data frame.

R CommandShort Description
length(x)Gives the number of elements in a variable $x$
mode(x)Tells about the data type of the variable $x$
nrow(x)Displays the number of rows of a vector, array, or data frame $x$
ncol(x)Displays the number of columns (variable) of a vector, array, or data frame $x$
dim(x)Displays the dimension (number of rows and columns) of a matrix, data frame, array, or list $x$
row(x)Matrix of row indices for matrix-like object $x$
col(x)Matrix of column indices for matrix-like object $x$
rownames(x)Get the row names of the matrix-like object $x$
rownames(x)=vSet the row names of the matrix-like object $x$ to $v$
colnames(x)Get the column names of the matrix-like object $x$
colnames(x)=vSet the column names of the matrix-like object $x$ to $v$
dimnames(x)Get both the row and column names (in a matrix, data frame, or list)
dimnames(x)=list(rn, cn)Set both the row and column names
names(x)Gives the names of $x$
namex(x)=vSets or resets the names of $x$ to $v$
names(x)=NULLremoves the names from $x$
row.names(df)Gives the observation names from a data frame
row.names(df)=vSets or resets the observation names of a data frame
names(df)Gives the variables names from a data frame
names(df)=vSets or resets the variable names of a data frame

R Language: A Quick Reference – I

https://itfeature.com, https://gmstat.com

Factors in R (Categorical Data): Learning Made Easy

Factors in R Language are used to represent categorical data in the R language. Factors in R can be ordered or unordered. One can think of a factor as an integer vector where each integer has a label. Factors are specially treated by modeling functions such as lm() and glm().  Factors are the data objects used for categorical data and stored as levels. They can store both string and integer variables. 

Using factors with labels is better than using integers as factors are self-describing; having a variable that has values “Male” and “Female” is better than a variable having values 1 and 2.

Creating a Simple Factor in R

The following example creates a simple factor variable that has two levels.

# Simple factor with two levels
x <- factor(c("yes", "yes", "no", "yes", "no"))
# computes frequency of factors
table(x)
# strips out the class
unclass(x)
Factors in R

The order of the levels can be set using the levels argument to factor(). This can be important in linear modeling because the first level is used as the baseline level.

x <- factor(c("yes","yes","no","yes","no"), levels = c("yes","no"))

Naming Factors in R

Factors can be given names using the label argument. The label argument changes the old values of the variable to a new one. For example,

x <- factor(c("yes", "yes", "no", "yes", "no"), levels = c("yes", "no"), label = c(1,2) )
x <- factor(c("yes","yes","no","yes","no"), levels = c("yes","no"), label = c("Level-1", "level-2"))

x <- factor(c("yes","yes","no","yes","no"), levels = c("yes","no"), label = c("group-1", "group-2"))

Suppose, you have a factor variable with numerical values. You want to compute the mean. The mean vector will result in the average value of the vector, but the mean of the factor variable will result in a warning message. To calculate the mean of the original numeric values of the "f" variable, you have to convert the values using the level argument. For example,

# vector
v <- c(10,20,20,50,10,20,10,50,20)
# vector converted to factor
f <- factor(v)
# mean of the vector
mean(v)

# mean of factor
mean(f)
mean(as.numeric(levels(f)[f]))

Use of cut() Function in R

The the cut() function in R can also be used to convert a numeric variable into a factor. The breaks argument can be used to describe how ranges of numbers will be converted to factor values. If the breaks argument is set to a single number then the resulting factor will be created by dividing the range of the variable into that number of equal-length intervals. However, if a vector of values is given to the breaks argument, the values in the vectors are used to determine the breakpoint. The number of levels of the resultant factor will be one less than the number of values in the vector provided to the breaks argument. For example,

attach(mtcars)
cut(mpg, breaks = 3)
factors <- cut(mpg, breaks = c(10, 18, 25, 30, 35) )
table(factors)
Factors in R using Cut Function

You will notice that the default label for factors produced by the cut() function in R contains the actual range of values that were used to divide the variable into factors.

Learn about Data Frames in R

https://itfeature.com

Introduction: Matrices in R

While dealing with matrices in R, all columns in the matrix must have the same mode (numeric, character, etc.), and the same length. A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the function matrix() in R.

The general syntax of creating matrices in R is:

matrix_name <- matrix(vector, nrow = r, ncol = c,
                         byrow = FALSE, dimnames = list(char_vector_rownames,
                                                        char_vector_colnames)
)

byrow = TRUE indicates that the matrix will be filled by rows.

dimnames provides optional labels for the columns and rows.

Creating Matrices in R

Following the general syntax of the function matrix() in R, let us create a matrix from a vector of the first 20 numbers.

Example 1:

# Generate matrix having 5 rows and 4 columns 
y1 <- matrix (1 : 20, nrow = 5, ncol = 4) ; y1

# Output
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
y2 <- matrix (1 : 20, nrow = 5, ncol = 4, byrow = FALSE); y2

# Output
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
y3 <- matrix (1 : 20, nrow = 5, ncol = 4, byrow = TRUE) ; y3

# Output
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
[4,] 13 14 15 16
[5,] 17 18 19 20

Example 2:

elements <- c(11, 23, 29, 67)
rownames <- c("R1", "R2")
colnames <- c("C1", "C2")

m1 <- matrix(elements, nrow = 2, ncol = 2, byrow = TRUE, 
      dimnames = list(rownames, colnames)
      )

# Output
   C1 C2
R1 11 23
R2 29 67

Try the above example 2 with the following values set to arguments as below

nrow = 4 and ncol = 1, byrow = FALSE

Note the difference. You may also have some errors related to the number of rows or columns. Therefore, if you change the number of rows or columns then ensure that you have the same number of row names and column names too.

Matrix Operations in R Language

In the R language, there are some operators and functions that can be used to perform computation on one or more matrices. Some basic matrix operations in R are:

Matrix OperationOperator/ Function
Add/ Subtract+, −
Multiply%*%
Transposet( )
Inversesolve ( )
Extract Diagonaldiag( ) It is described at the end too
Determinantdet( )

The following are some examples related to these operators and matrix functions.

m1 <- matrix(c(11, 23, 9, 35), nrow = 2)
m2 <- matrix(c(5, 19, 11, 20), nrow =2)
m3 <- m1 + m2
m4 <- m1 - m2
m5 <- m1 %*% m2
m6 <- m1 / m2
m1t <- t(m1)
m1tminv <- solve(m1t %*% m1)
diag(m1tminv)

# Output
> m1
     [,1] [,2]
[1,]   11    9
[2,]   23   35

> m2
     [,1] [,2]
[1,]    5   11
[2,]   19   20

> m3
     [,1] [,2]
[1,]   16   20
[2,]   42   55

> m4
     [,1] [,2]
[1,]    6   -2
[2,]    4   15

> m5
     [,1] [,2]
[1,]  226  301
[2,]  780  953

> m6
         [,1]      [,2]
[1,] 2.200000 0.8181818
[2,] 1.210526 1.7500000

> m1t
     [,1] [,2]
[1,]   11   23
[2,]    9   35
Introduction: Matrices in R

Some other important functions can be used to perform some required computations on matrices in R. These matrix operations in R are described below for matrix $X$. You can use your matrix.

Consider we have a matrix X with elements.

X <- matrix(1:20, nrow = 4, ncol = 5) 
X
FunctionDescription
rowSums(X)Compute the average value of each column of the Matrix $X$
colSums(X)Compute the average value of each row of the Matrix $X$
rowMeans(X)Compute the average value of each column of the Matrix $X$
colMeans(X)Compute the average value of each column of the Matrix $X$
diag(X)Extract diagonal elements of the Matrix $X$, or
Create a Matrix that has required diagonal elements such as diag(1:5), diag(5),
crossprod(X,X)Compute X‘X. It is a shortcut of t(X)%*%X

Obtaining Regression Coefficients using Matrices in R

Consider we have a dataset that has a response variable and few regressors. There are many ways to create data (or variables), such as one can create a vector for each variable, a data frame for all of the variables, matrices, or can read data stored in a file.

Here we try it using vectors, then bind the vectors where required. We will use matrices to obtain the regression coefficients.

y  <- c(5, 6, 7, 9, 8, 4, 3, 2, 1, 6, 0, 7)
x1 <- c(4, 5, 6, 7, 8, 3, 4, 9, 9, 8, 7, 5)
x2 <- c(10, 22, 23, 10, 11, 14, 15, 16, 17, 12, 11, 17)
x  <- cbind(1, x1, x2)

The cbind( ) function is used to create a matrix x. Note that 1 is also bound to get the intercept term (the model with the intercept term). Let us compute $\beta$’s from OLS using matrix functions and operators.

xt <- t(x)
xtx <- xt %*% x
xtxinv <- solve(xtx)
xty <- xt %*% y
b <- xtxinv %*% xty

The output is

#Output
x
        x1 x2
 [1,] 1  4 10
 [2,] 1  5 22
 [3,] 1  6 23
 [4,] 1  7 10
 [5,] 1  8 11
 [6,] 1  3 14
 [7,] 1  4 15
 [8,] 1  9 16
 [9,] 1  9 17
[10,] 1  8 12
[11,] 1  7 11
[12,] 1  5 17

xt
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
      1    1    1    1    1    1    1    1    1     1     1     1
x1    4    5    6    7    8    3    4    9    9     8     7     5
x2   10   22   23   10   11   14   15   16   17    12    11    17

xtx
         x1   x2
    12   75  178
x1  75  515 1103
x2 178 1103 2854

xtxinv
xty
b
Computing regression coefficient, matrices in R

Data Structure Matrix in R

visit https://gmstat.com