Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dataframe to matrix without column names

Tags:

r

matrix

I would like to convert a dataframe into a numeric-only matrix. My goal:

num [1:3, 1:4] 1 2 3 1 2 3 1 2 3 1 ...

And that's all.

alpha <- beta <- gamma <- delta <- c(1,2,3)
df <- data.frame(alpha, beta, gamma, delta, stringsAsFactors = FALSE)

M1 <- as.matrix(df, ncol = ncol(df))
str(M1)

M2 <- data.matrix(df)
str(M2)

num [1:3, 1:4] 1 2 3 1 2 3 1 2 3 1 ... - attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:4] "alpha" "beta" "gamma" "delta"

I can't for the life of me figure out how to do it without all the attributes. I need the pure form as input to another method.

like image 424
Robert Hadow Avatar asked May 08 '19 23:05

Robert Hadow


People also ask

How do I remove column names?

Select any column header, and then select Column settings > Show/hide columns. Select the column header you want to delete and select Column settings > Edit > Delete.

How do you convert a Dataframe to a matrix?

Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.

How do I remove column names from a matrix in R?

To remove the row names or column names from a matrix, we just need to set them to NULL, in this way all the names will be nullified.

How do I remove column headings in R?

To remove the columns names we can simply set them to NULL as shown in the below examples.


1 Answers

@thelatemail was absolutely right.

unname(as.matrix(df))

Does the trick.

like image 138
Robert Hadow Avatar answered Sep 25 '22 20:09

Robert Hadow