Reputation: 387
Could you please help me?
I frequently need to read incidence matrices (AxB) into R
formatted as TXT files. They look like this:
matrix <- matrix(round(runif(50, 0, 100),0), 5, 10)
My usual solution involves base's read.delim
and as.matrix
:
as.matrix(read.delim("matrix.txt", row.names = 1))
The file is read and converted to matrix
class, so the proper analyses can be carried out.
However, I would like to be able to read a matrix file also using tidyverse's read_delim
, so the reading process can be faster for large matrices or a large number of matrices. I've tried this:
as.matrix(read_delim("matrix.txt", delim = "/t"))
But the data get scrambled in a very strange format, and the information is lost. Is there a way to read and work with incidence matrices
using tidyverse tools?
Thank you!
Upvotes: 1
Views: 1143
Reputation: 97
try this
as.matrix(read_delim("matrix.txt", delim = "\t", col_names = F))
Upvotes: 1
Reputation: 5747
In R, you need to use backslash to denote the special and escape characters.
Try
as.matrix(read_delim("matrix.txt", delim = "\t"))
The read_delim
function does not have a row.names option, so you will have to transform the data to get your rownames as rownames (and not the first column). You should do this before you convert to matrix.
library(tidyverse)
matrix <- read_delim("matrix.txt", delim = "\t") %>%
column_to_rownames(first_column) %>%
as.matrix()
Upvotes: 1