Clayton Glasser
Clayton Glasser

Reputation: 193

How to create a matrix with specified row and col names, from a dataframe containing the data and the names

If I have a dataframe like so:

dataframe <- data.frame(Date = seq(as.Date("2018/01/01"), by = "day", length.out = 5),
                        ID1 = c(1, 2, 3, 4, 5),
                        ID2 = c(6, 7, 8, 9, 10))

> dataframe
        Date ID1 ID2
1 2018-01-01   1   6
2 2018-01-02   2   7
3 2018-01-03   3   8
4 2018-01-04   4   9
5 2018-01-05   5  10

What is the best way to convert it into a matrix, with the observations as the data, Dates as row names, and the IDs as col names?

I'd think there would be a function that converted dataframes and took certain column/rows as arguments for col/row names, but I have not found that.

Bonus question: Do I need to have a distinct matrix for each ID? Do I need to create a 3D array or similar? How could I do that?

Upvotes: 1

Views: 874

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270248

First set the row names and then convert it to matrix:

as.matrix(data.frame(dataframe[-1], row.names = dataframe$Date))

Another possibility is to use a zoo or xts object. This will create a matrix for the data and define an index attribute for the dates. The resulting object is of class zoo and can be manipulated by the functions of the zoo package.

library(zoo)
z <- read.zoo(dataframe)

Upvotes: 1

Related Questions