Skip to content

Named append #99

@hadley

Description

@hadley

It would be useful to have some way to add a single column to a specific position in a data frame.

Here's a basic implementation that does what I want, but could clearly be optimised.

insert_col <- function(data, x, after, name = deparse(substitute(x))) {
  as.data.frame(append(data, setNames(list(x), name), after))
}

mtcars %>% insert_col(1:32, 0, "id")

The example gives something I want to do fairly commonly: insert an id column at the front of a data frame. The name of the id column is often given by a variable, so it's useful to have an interface that doesn't use names.

It might also be useful to have insert_cols() which worked like append, but preserved the output class. That would be useful if you had multiple columns you wanted to insert.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions