Skip to content

read.table or read.csv without row index?

4 messages · vincent.deluard, Jo Frabetti, David Winsemius

#
Hi,

I have the same problem as Wong.

I have a csv file that contains weather observation (rows) by days (in
columns).

I open using:
and read:

             X X1.Jan X2.Jan X3.Jan X4.Jan
1          Min      2      3      4      1
2          Max      6     10      8      6
3 Forecast Min      3      1      1      3
4 Forecast Max      8      7      4      9 

If I type

mean(temp[2,2:3])

I get

X1.Jan X2.Jan 
     6     10 

The same command on
[1] 6.5

works because the data is in a matrix. So how do I convert the data from my
csv file into a matrix?
I tried as.matrix but it did not help.


Many many thanks!
#
as.matrix() won't work because a matrix requires everything in it to
be of the same type (number, character, logical etc.). You do not have
only numbers in your data.frame, so it will convert everything to
character strings. If you try as.matrix(temp[,-1]) it should work
(assuming you only have characters in the first column, otherwise
remove all non-numeric columns).

But what you really want is to circumvent the fact that, on a
data.frame, mean works column-wise. In fact, when you call mean() on a
data.frame() it calls mean.data.frame(), which code you can see by
typing its name at the prompt:

    > mean.data.frame
    function (x, ...)
    sapply(x, mean, ...)
    <environment: namespace:base>

And indeed, it uses sapply() to apply the function mean to each
column. You could have tried:

    mean.default(temp[2,2:3])

but this returns and error because it needs a numeric vector and does
not automatically convert your data.frame into it. So you need:

    mean.default(as.numeric(temp[2,2:3]))

or more simply

    mean(as.numeric(temp[2,2:3]))

I hope that helped. Sincerely,

JiHO
---
http://maururu.net
#
On May 5, 2010, at 3:49 PM, JiHO wrote:

            
Or:

mean( data.matrix(temp)[ 2 , 2:3] )
David Winsemius, MD
West Hartford, CT