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

Rolf Turner rolf.turner at xtra.co.nz
Wed Apr 10 00:24:28 CEST 2013


Interesting.  The problem is that only ***arrays*** are allowed to have
a dimnames attribute, and data frames are not arrays (they are lists).

The only way that I can see to achieve the effect that you want is to
make the row names into the first column of your data frame and wipe
out the row names.  That is probably the "ugly" procedure that you've
already thought of.

You could automate the procedure to some extent:

fixUpRowNames <- function(X,name) {
X <- as.data.frame(X)
X <- cbind(rownames(X),X)
names(X)[1] <- name
rownames(X) <- NULL
X
}

Then do:

tableData <- state.x77[c(7, 38, 20, 46), c(7, 1, 8)]
newTD <- fixUpRowNames(tableData,"State")

And then all is (more or less) in harmony.

Best that I can come up with.

     cheers,

         Rolf Turner

On 04/10/2013 08:52 AM, Paul Miller 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.



More information about the R-help mailing list