[R] Converting matrix to data frame without losing an assigned dimname

Gabor Grothendieck ggrothendieck at gmail.com
Tue Apr 9 23:42:20 CEST 2013


On Tue, Apr 9, 2013 at 4:52 PM, Paul Miller <pjmiller_57 at yahoo.com> wrote:
> Hello All,
>
> Would like to be able to convert a matrix to a dataframe without losing an assigned dimname.
>
> Here is an example that should illustrate what I'm talking about.
>
> tableData <- state.x77[c(7, 38, 20, 46), c(7, 1, 8)]
> names(dimnames(tableData)) <- c("State", "")
> tableData
>
> State          Frost Population  Area
>   Connecticut    139       3100  4862
>   Pennsylvania   126      11860 44966
>   Maryland       101       4122  9891
>   Virginia        85       4981 39780
>
> tableData <- as.data.frame(tableData)
> tableData
>
>              Frost Population  Area
> Connecticut    139       3100  4862
> Pennsylvania   126      11860 44966
> Maryland       101       4122  9891
> Virginia        85       4981 39780
>
> Notice how "State" gets removed when converting to a dataframe. How can I get a dataframe with a separate column called "State" instead of having the state become the row.names? I can think of an ugly way to do it but suspect there must be something more elegant.
>

Try this:

> library(plyr)
> adply(tableData, 1, c)
         State Frost Population  Area
1  Connecticut   139       3100  4862
2 Pennsylvania   126      11860 44966
3     Maryland   101       4122  9891
4     Virginia    85       4981 39780

--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list