Roy
Roy

Reputation: 867

Converting a list to a numeric matrix in r

I cannot seem to convert a list to a matrix. I load a .csv file using:

dat = read.csv("games.csv", header = TRUE)

> typeof(dat)
[1] "list"

But when I try to convert it into a numeric matrix using:

games = data.matrix(dat)

The entries' values are all changed for some reason. What is the problem?

Upvotes: 0

Views: 3943

Answers (2)

hrbrmstr
hrbrmstr

Reputation: 78842

While Nathaniel's solution worked for you, I think it's important to point out that you might need to adjust your perception of what is going on.

The typeof(dat) might be a list but the class is a data.frame.

This might help illustrate the difference:

# typeof() & class() of `pts` is `list`
# whereas typeof() `dat` in your example is `list` but
# class() of `dat` in your example is a `data.frame`

pts <- list(x = cars[,1], y = cars[,2])

as.matrix(pts)
##   [,1]      
## x Numeric,50
#3 y Numeric,50

head(as.matrix(data.frame(pts)))
##      x  y
## [1,] 4  2
## [2,] 4 10
## [3,] 7  4
## [4,] 7 22
## [5,] 8 16
## [6,] 9 10

Those are two substantially different outcomes from the 'as.matrix()` function.

Just making sure you don't get disappointed of the outcome if you try this in a different context outside of read.csv.

Upvotes: 2

Nathaniel Payne
Nathaniel Payne

Reputation: 2827

Without any other information being provided, perhaps you might try:

games <- as.matrix(dat)

Upvotes: 1

Related Questions