[R] extracting named vector from dataframe

David Winsemius dwinsemius at comcast.net
Sun Oct 31 17:23:42 CET 2010


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