How to create Vectors, Factors, Lists, Matrices and Datasets with R Programming

In this post, we will show how to create vectors, factors, lists, matrices and datasets in R.

Vectors

The vector is a very important tool in R programming. Through vectors, we create matrices and data frames.
Vectors can have numeric, character, and logical values. The function c() is used to create vectors in R programming.

For example, let’s create a numeric vector:

# numeric
x <- c(1, 3, 2, 5.2, -4, 5, 12)
x
1  3  2  5.2 -4  5 12

We can also have a character vector:

# character
y <- c("red", "blue", "green", "no color")
y
"red" "blue" "green" "no color"

Finally, we can create logical vectors:

# logical
z <- c(TRUE, TRUE, FALSE)
z
TRUE TRUE FALSE

Additionally, you can create a vector which combines numeric and character values. We can also check whether the vector is numeric or character. As the output shows, when numbers and characters are combined, all elements are converted to character, so the vector is no longer numeric.

# numeric and character
x <- c(1, 2.2, "blue")
x
# check if it is numeric
is.numeric(x)
# check if it is character
is.character(x)
"1" "2.2" "blue"
FALSE
TRUE

Sometimes we might be interested to know how many elements a vector has — in other words, the length of the vector.

x <- c(1,2,6,4,7)
length(x)
5

A simple way to generate a vector in arithmetic progression is to use the seq() function.

x <- seq(from=2, to=10, by=2)
x
2 4 6 8 10

Factors

Factors are similar to vectors in R, but they have an additional meaning: factors have levels. Levels are widely used in medical research, where they carry an important meaning. For example, smoking status could have 3 levels: never smoker, former smoker, and current smoker. When we code smoking, we can write 0, 1, and 2 for never, former, and current smoker, respectively. To create a factor, the function factor() is used.

Create a vector with 6 elements:

s <- c(0, 1, 2, 1, 0, 0)
s
0 1 2 1 0 0

To turn these values into a factor, use the function factor:

sf <- factor(s)
sf
0 1 2 1 0 0
Levels: 0 1 2

When you conduct your analysis, make sure that you have coded your factors accurately.

Lists

Lists are vectors, but unlike ordinary vectors, lists can combine different types of objects. For example, let’s suppose that we want to create a list of medical records. A medical record contains the diagnosis, age, and treatment of a patient.

The function to create lists is list().

x <- list(diagnosis="Gastritis", age=79, medication=TRUE)
x
$diagnosis
"Gastritis"
$age
79
$medication
TRUE

Now that you have created a list, let’s see how we can work with it. You may want to access individual elements of the list.

x$age
x$medication
79
TRUE

Sometimes you may want to know the size of the list; for this, use the function length.

length(x)
3

Matrices

Matrices are vectors with more than one dimension; therefore, matrices have rows and columns. To define the number of rows and columns, you use the arguments nrow and ncol, respectively. Similarly to vectors, matrices can contain numbers, characters, and logical values.

# create matrix with 6 elements
y <- matrix(1:6, nrow=3, ncol=2)
y
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

Or you can simply create a matrix like this, specifying only the number of rows:

# create matrix with 10 elements
y <- matrix(1:10, nrow=2)
# number of row is 2, than the columns will be 5
y
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

Another way of creating matrices is by using the column-binding function cbind() or the row-binding function rbind().

# create vectors
x <- 2:5
y <- 9:12
# sort by rows
rbind(x,y)
# sort by columns
cbind(x,y)
[,1] [,2] [,3] [,4]
x    2    3    4    5
y    9   10   11   12

 x  y
[1,] 2  9
[2,] 3 10
[3,] 4 11
[4,] 5 12

You can also create a matrix in yet another way, by defining the vector of values together with the names of the columns and rows.

# create matrix with 4 elements
cells <- c(2,5,12,30)
colname <- c("Jan", "Feb")
rowname <- c("Apple", "Orange")
y <- matrix(cells, nrow=2, ncol=2, byrow=TRUE, dimnames=list(rowname, colname))
y
       Jan Feb
Apple    2   5
Orange  12  30

As you can see above, the argument byrow=TRUE fills the cells row by row; you can set it to FALSE to fill them column by column instead.

Datasets

Datasets are similar to matrices but, in comparison with a matrix, a data frame can contain both numeric and character elements. Therefore, a data frame can have one column with numbers and another column with characters. The function used to create data frames is data.frame().

Let’s create a simple dataset.

hospital <- c("New York", "California")
patients <- c(150, 350)
df <- data.frame(hospital, patients)
df
hospital   patients
New York        150
California      350

Frequently we are interested in looking at the structure of the dataset we use, and for this we use the function str():

str(df)
'data.frame':	2 obs. of  2 variables:
 $ hospital: Factor w/ 2 levels "California","New York": 2 1
 $ patients: num  150 350

Here we end this post. Post a comment if you have any questions.

KD
Author
Klodian Dhana

Creator of DataScience+, a home for R and Python enthusiasts to share their knowledge with the world since 2015. I also publish tutorials in R and the tidyverse on the topics I find most interesting.

27 articles on DataScience+
View all posts

4 Comments

  1. S
    shesaidsomething January 29, 2019

    Succinct overview. Easily understood. A+

    (very polite corrections – nice to see civility 😉

    Reply
  2. JF
    Jason Friedman September 13, 2018

    Thanks for the tutorial. The output of this command:

    s <- c(0, 1, 2, 1, 0, 0)

    should be this:

    0 1 2 1 0 0

    Reply
  3. K
    kyste November 1, 2015

    Thanks for the tutorial, in the

    # create matrix with 4 elements in the y creation one “)” is missing at the end of the line, and I think you don’t need to put colname and rowname between “”.
    Best regards

    Reply
    1. K
      Klodian November 1, 2015

      True. Thanks for the update.

      Reply

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.