Description Usage Arguments Value Author(s) Examples
View source: R/create_tmp_name.R
Adds underscore to name
until it is unique in data
.
Use case: Adding a temporary index column to a data frame within a function, where you don't want to overwrite an existing column.
1 | create_tmp_name(data, name = ".tmp_")
|
data |
Any data structure where names can be
accessed with |
name |
Initial name to try.
If it's already in |
Name not already in data
.
Ludvig Renbo Olsen, r-pkgs@ludvigolsen.dk
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | # Attach packages
library(rtilities2)
# Create data frame
df <- data.frame("a" = c(1, 2), "b" = c(2, 3))
# Create named list
nl <- list("a" = c(1, 2), "b" = c(2, 3))
# Create unique name for the data frame
# As "a" is already in df, it appends a "_"
create_tmp_name(df, "a")
# Create unique name for the list
# As "a" is already in df, it appends a "_"
create_tmp_name(nl, "a")
# Using it within a function
# in order not to overwrite a user's column
foo <- function(data) {
# Create unique temporary name
tmp_colname <- create_tmp_name(data, ".tmp_index_")
# Create index column with the name
data[[tmp_colname]] <- seq_len(nrow(data))
# Do something that reorders the data set
data <- dplyr::sample_frac(data)
# Order by the temporary index
data <- dplyr::arrange_at(data, tmp_colname)
# Remove the temporary index
data[[tmp_colname]] <- NULL
data
}
foo(df)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.