Quantcast

Convert Row Names to data.frame column

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Convert Row Names to data.frame column

chipmaney
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?
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Convert Row Names to data.frame column

David Winsemius

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

______________________________________________
[hidden email] 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.
Loading...