Permalink
Browse files

Implement name_rows to save and restore row names.

Fixes #61
  • Loading branch information...
1 parent a3bcf94 commit beae4a6bd363cd0f4be838f2cf4b10209e968581 @hadley committed Oct 8, 2012
Showing with 65 additions and 0 deletions.
  1. +1 −0 DESCRIPTION
  2. +1 −0 NAMESPACE
  3. +2 −0 NEWS
  4. +33 −0 R/helper-name-rows.r
  5. +28 −0 man/name_rows.Rd
View
@@ -78,3 +78,4 @@ Collate:
'parallel.r'
'join_all.r'
'progress-time.r'
+ 'helper-name-rows.r'
View
@@ -71,6 +71,7 @@ export(match_df)
export(mdply)
export(mlply)
export(mutate)
+export(name_rows)
export(numcolwise)
export(progress_none)
export(progress_text)
View
@@ -1,6 +1,8 @@
Version 1.7.1.99
------------------------------------------------------------------------------
+* `name_rows` provides a convenient way of saving and then restoring row names so that you can preserve them if you need to. (#61)
+
* `*aply` now accepts 0-dimension arrays as outputs. (#88)
* new `progress_time` function that estimates the amount of time remaining before the job is completed. (Thanks to Mike Lawrence, #78)
View
@@ -0,0 +1,33 @@
+#' Toggle row names between explicit and implicit.
+#'
+#' Plyr functions ignore row names, so this function provides a way to preserve
+#' them by converting them to an explicit column in the data frame. After the
+#' plyr operation, you can then apply \code{name_rows} again to convert back
+#' from the explicit column to the implicit \code{rownames}.
+#'
+#' @param df a data.frame, with either \code{rownames}, or a column called
+#' \code{.rownames}.
+#' @export
+#' @examples
+#' name_rows(mtcars)
+#' name_rows(name_rows(mtcars))
+#'
+#' df <- data.frame(a = sample(10))
+#' arrange(df, a)
+#' arrange(name_rows(df), a)
+#' name_rows(arrange(name_rows(df), a))
+name_rows <- function(df) {
+ stopifnot(is.data.frame(df))
+
+ rn_col <- !is.null(df$.rownames)
+
+ if (rn_col) {
+ rownames(df) <- df$.rownames
+ df$.rownames <- NULL
+ } else {
+ df$.rownames <- rownames(df)
+ rownames(df) <- NULL
+ }
+
+ df
+}
View
@@ -0,0 +1,28 @@
+\name{name_rows}
+\alias{name_rows}
+\title{Toggle row names between explicit and implicit.}
+\usage{
+ name_rows(df)
+}
+\arguments{
+ \item{df}{a data.frame, with either \code{rownames}, or a
+ column called \code{.rownames}.}
+}
+\description{
+ Plyr functions ignore row names, so this function
+ provides a way to preserve them by converting them to an
+ explicit column in the data frame. After the plyr
+ operation, you can then apply \code{name_rows} again to
+ convert back from the explicit column to the implicit
+ \code{rownames}.
+}
+\examples{
+name_rows(mtcars)
+name_rows(name_rows(mtcars))
+
+df <- data.frame(a = sample(10))
+arrange(df, a)
+arrange(name_rows(df), a)
+name_rows(arrange(name_rows(df), a))
+}
+

0 comments on commit beae4a6

Please sign in to comment.