create_tmp_name: Create unique temporary name

Description Usage Arguments Value Author(s) Examples

View source: R/create_tmp_name.R

Description

\Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}

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.

Usage

1

Arguments

data

Any data structure where names can be accessed with names(). E.g. a data frame or list.

name

Initial name to try. If it's already in data, an underscore will be appended until it is unique.

Value

Name not already in data.

Author(s)

Ludvig Renbo Olsen, r-pkgs@ludvigolsen.dk

Examples

 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)

LudvigOlsen/rtilities2 documentation built on Jan. 19, 2020, 4:57 a.m.