[R] Convert Row Names to data.frame column

David Winsemius dwinsemius at comcast.net
Sat Jul 24 00:29:38 CEST 2010


On Jul 23, 2010, at 6:18 PM, chipmaney wrote:

>
> Here is an example dataset:
>
> ZoneCover.df<- data.frame(Value=c(1,2))
> row.names(ZoneCover.df) <- c("Floodplain1.Tree", "Floodplain1.Shrub")
>
>
> I want to Export the Row.Names to a column in the dataframe:
>
> ZoneCover.df$ID <- names(ZoneCover.df)
>
> which yields this:
>
>> ZoneCover.df
>                  Value                ID
> Floodplain1.Tree      1  Floodplain1.Tree
> Floodplain1.Shrub     2 Floodplain1.Shrub
>
>
> QUESTION:
>
> How do I remove the .Tree and .Shrub extensions from the ZoneCover$ID
> values?

?gsub
?regex

(The "." character needs to be "escaped" with doubled "\" but the  
second "." is a regex for any character.)

 > gsub("\\..*$","", c("Floodplain1.Tree", "Floodplain1.Shrub"))
[1] "Floodplain1" "Floodplain1"

Use the same method with assignment to the column:

ZoneCover.df$ID <-  gsub("\\..*$","", ZoneCover.df$ID)
--

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list