Skip to content
Back to formatted view

Raw Message

Message-ID: <556C9CFF-77A3-438C-BA9D-25F51F722317@comcast.net>
Date: 2012-08-28T04:03:15Z
From: David Winsemius
Subject: write.table and read.table commands
In-Reply-To: <901D4451-635C-4C5D-8E38-DCD2247F8AEB@gmail.com>

On Aug 27, 2012, at 10:04 PM, R. Michael Weylandt <michael.weylandt at gmail.com 
 > wrote:

> It's because read.table returns a data frame, not a matrix. You can  
> coerce to a matrix with as.matrix() but you might loose information  
> if your variables are of different classes.
>
> Michael
>
> On Aug 27, 2012, at 7:07 PM, Cheryl Johnson <johnson.cheryl625 at gmail.com 
> > wrote:
>
>> Greetings,
>>
>> When I try to use the write.table command to save a matrix as a  
>> file and
>> then open the file with read.table, if I try to take the mean of  
>> the entire
>> matrix, instead each column of the matrix has its mean calculated.  
>> I have
>> copied and pasted an example of my code below. When I try to make the
>> header false with the read.table command, I am given an error  
>> message. I
>> would appreciate any guidance for how to average the entire matrix  
>> instead
>> of just the columns.
>>
>> Thanks
>>
>> z=matrix(1:20,4,5)
>> write.table(z,  
>> file="exercise.csv",sep=",",col.names=NA,qmethod="double")
>> j=read.table("exercise.csv",header=T,sep=",",row.names=1)
>> mean(j)
>>
>> V1   V2   V3   V4   V5
>> 2.5  6.5 10.5 14.5 18.5
>> Warning message:
>> mean(<data.frame>) is deprecated.
>> Use colMeans() or sapply(*, mean) instead.

Notice that the error message was telling you that there was a  
`mean.data.frame` function which is slated for removal (perhaps) in  
the next version of R.

You can read about its  behavior:

?mean.data.frame


You could have gotten the desired behavior with:

mean(mean(j))

Or by saving the z object and load it as an Rdata file.

Or with

 > z=matrix(1:20,4,5)
 > write.table(z, file="exercise.csv",sep=",",row.names=FALSE,  
col.names=FALSE)
 > j=scan("exercise.csv",sep=",", what=double())
Read 20 items
 > mean(j)
[1] 10.5

(Although the numbers are now in a vector.)


>>   [[alternative HTML version deleted]]


David Winsemius, MD
Alameda, CA, USA