[R] extracting named vector from dataframe

James Hirschorn James.Hirschorn at hotmail.com
Sun Oct 31 19:06:22 CET 2010


Of course you are right that this would not be appropriate in general, but
what I'm doing--which as Baptiste explained can be done much more nicely
with unlist()---seems reasonable in my context: The dataframe has a computed
statistic for each input, but I need a vector so that I can do operations
such as sort().

-----Original Message-----
From: David Winsemius [mailto:dwinsemius at comcast.net] 
Sent: Sunday, October 31, 2010 12:24 PM
To: James Hirschorn
Cc: R-help at r-project.org
Subject: Re: [R] extracting named vector from dataframe


On Oct 31, 2010, at 11:54 AM, James Hirschorn wrote:

> Suppose df is a dataframe with one named row of numeric  
> observations. I want
> to coerce df into a named vector.

I don't think you understand the structure of dataframes. They are  
named lists of component columns. The names you are attributing to the  
rows are not attached to the observations but rather are column names.  
So that row is not in any sense a "named vector". If you created a  
dataframe with the first column a named vector its names would become  
the rownames.

>
> as.vector does not work as I expected: as.vector(df) returns the  
> original
> dataframe, while as.vector(df,mode="numeric") returns an unnamed  
> vector of
> NAs.
>
> This works:
>
>> v <- as.numeric(as.matrix(df)); names(v) <- names(df);
>
Right. You are now assigning the column names to the elements in a  
row, but in some ways that is an unnatural act, and not something that  
would be expected to work in the general case where a "row" might be a  
diverse set of types and even different classes. Your as.matrix  
operation coerced all of the values to be of one type.
>
> I just wanted check if there was a better/more natural way of doing  
> this?

--

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list