- Assigning Objects
We can create new data objects and variables quite easily within R. We use the = or the → operator to denote assigning an object to it’s name. For the purpose of this article we will use = to assign objectnames and objects. This is very useful when we are doing data manipulation as we can reuse the manipulated data as inputs for other steps in our analysis.
Types of Data Objects in R
- Lists
A list is simply a collection of data. We create a list using the c operator.
The following code creates a list named numlist from 6 input numeric data
numlist=c(1,2,3,4,5,78)
The following code creates a list named charlist from 6 input character data
charlist=c(“John”,”Peter”,”Simon”,”Paul”,”Francis”)
The following code creates a list named mixlistfrom both numeric and character data.
mixlist=c(1,2,3,4,”R language”,”Ajay”)
- Matrices
Matrix is a two dimensional collection of data in rows and columns, unlike a list which is basically one dimensional. We can create a matrix using the matrix command while specifying the number of rows by nrow and number of columns by ncol paramter.
In the following code , we create an matrix named ajay and the data is input in 3 rows as specified, but it is entered into first column, then second column , so on.
ajay=matrix(c(1,2,3,4,5,6,12,18,24),nrow=3)
ajay
[,1] [,2] [,3]
[1,] 1 4 12
[2,] 2 5 18
[3,] 3 6 24
However please note the effect of using the byrow=T (TRUE) option. In the following code we create an matrix named ajay and the data is input in 3 rows as specified, but it is entered into first row, then second row , so on.
>ajay=matrix(c(1,2,3,4,5,6,12,18,24),nrow=3,byrow=T)
>ajay
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 12 18 24
- Data Frames
A data frame is a list of variables of the same number of rows with unique row names. The column names are the names of the variables.