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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to