Vector, Array, List and Data Frame in R

Vector, Array, List and Data Frame are 4 basic data types defined in R. Knowing the differences between them will help you use R more efficiently.

1. Vector

All elements must be of the same type.

For example, the following code create two vectors.

name <- c("Mike", "Lucy", "John") 
age <- c(20, 25, 30) 

2. Array & Matrix

Matrix is a special kind of vector. A matrix is a vector with two additional attributes: the number of rows and the number of columns.

> x <- matrix(c(1,2,3,4), nrow=2, ncol=2)
> x
     [,1] [,2]
[1,]    1    3
[2,]    2    4

Similar to matrix, but arrays can have more than two dimensions.

3. List

List can contain elements of different types.

> y <- list(name="Mike", gender="M", company="ProgramCreek")
> y
[1] "Mike"
[1] "M"
[1] "ProgramCreek"

4. Date Frame

A data frame is used for storing data tables. It is a list of vectors of equal length.

For example, you can create a date frame by using the following code:

> name <- c("Mike", "Lucy", "John") 
> age <- c(20, 25, 30) 
> student <- c(TRUE, FALSE, TRUE) 
> df = data.frame(name, age, student)  
> df
  name age student
1 Mike  20    TRUE
2 Lucy  25   FALSE
3 John  30    TRUE
Category >> R  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • mimi

    “matrix is a special kind of vector.” this statement is not correct.
    matrix is ​​a larger category than vector. It is a kind of inclusive relationship.

  • renceokgobja

    Thanks for that. Makes sense now

  • Krishna Praveen

    if you want it the second way you have to add another argument “byrow=TRUE” .By default r takes column wise

  • renceokgobja

    In your example,
    x <- matrix(c(1,2,3,4), nrow=2, ncol=2)

    > x
    [,1] [,2]
    [1,] 1 3
    [2,] 2 4

    Why can’t it be

    > x
    [,1] [,2]
    [1,] 1 2
    [2,] 3 4

    Does R implicitly assign columns first?

  • gamebusterz

    Clear and short explanation. Thanks