R/compose_data.R
n_prefix.RdGenerates a function for generating names of index columns for factors in
compose_data() by prefixing a character vector to the original
column name.
n_prefix(prefix)Character vector to be prepended to column names by
compose_data() to create index columns. Typically something
like "n" (that is the default used in the .n_name argument
of compose_data()).
Returns a function. The function returned takes a character vector, name
and returns paste0(prefix, "_", name), unless name is empty, in
which case it will return prefix.
n_prefix("n") is the default method that compose_data() uses to
generate column names for variables storing the number of levels in a factor. Under
this method, given a data frame
df with a factor column "foo" containing 5 levels, the results of
compose_data(df) will include an element named "n" (the result of
n_prefix("n")("")) equal to the number of rows in df and an element
named "n_foo" (the result of n_prefix("n")("foo")) equal to the
number of levels in df$foo.
The .n_name argument of compose_data().
library(magrittr)
df = data.frame(
plot = factor(paste0("p", rep(1:8, times = 2))),
site = factor(paste0("s", rep(1:4, each = 2, times = 2)))
)
# without changing `.n_name`, compose_data() will prefix indices
# with "n" by default
df %>%
compose_data()
#> $plot
#> [1] 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
#>
#> $n_plot
#> [1] 8
#>
#> $site
#> [1] 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4
#>
#> $n_site
#> [1] 4
#>
#> $n
#> [1] 16
#>
# you can use n_prefix() to define a different prefix (e.g. "N"):
df %>%
compose_data(.n_name = n_prefix("N"))
#> $plot
#> [1] 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
#>
#> $N_plot
#> [1] 8
#>
#> $site
#> [1] 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4
#>
#> $N_site
#> [1] 4
#>
#> $N
#> [1] 16
#>