0
votes

I want to read a matrix (all values, no null or empty column) from a tab-separated text file of integers and name the columns automatically (based on the titles in the first line):

a   b   c
9   2   3
2   9   6
3   2   4
5   3   3

I have tried read.csv(), read.table() and scan() methods and read the file, but I want something that:

1- Automatically identifies the column names (no need to mention the names one by one).

2- I would be able to treat them as matrix of integers; run rcorr(data) and quantile(data$a, 0.9) instead of rcorr(as.matrix(data)) and quantile(as.matrix(data$a), 0.9) any time.

Any ideas on the simplest (yet efficient) way?

2
I'm sort of at a loss as to what the big problem is with using read.table and then just coercing it to a matrix...?joran
txt <- "a\tb\tc\n9\t2\t3\n2\t9\t6\n3\t2\t4\n5\t3\t3" is your data (see cat(txt) ) - as.matrix(read.table(text=txt,sep="\t",header=TRUE)) will work fine and give you exactly what you want.thelatemail
@thelatemail: you are right. Thank you. I just figured out the problem which was a special character (#) in the header titles.Alisa
@joran, Thanx. See the other comment.Alisa

2 Answers

1
votes

How about read.table?

read.table(text="a b c
                 9 2 3
                 2 9 6
                 3 2 4
                 5 3 3", header=TRUE)

>      a b c
     1 9 2 3
     2 2 9 6
     3 3 2 4
     4 5 3 3

it also has options to input file, declare the separator, etc.. see help(read.table)

0
votes
data <-- as.matrix(read.table("c:\\temp\\inFile.tsv", header=TRUE))

Note that I got the following error when there was special characters (#) in the header line:

Error in read.table("..."), : more columns than column names

So there shouldn't be special characters in the header line. Also it automatically detects the separator ("\t").