Skip to contents

Reformat Values

Usage

reformat(obj, ...)

# S3 method for default
reformat(obj, format, ...)

# S3 method for character
reformat(obj, format, string_as_fct = TRUE, na_last = TRUE, ...)

# S3 method for factor
reformat(obj, format, na_last = TRUE, ...)

# S3 method for dm
reformat(obj, format, string_as_fct = TRUE, na_last = TRUE, ...)

# S3 method for list
reformat(obj, format, string_as_fct = TRUE, na_last = TRUE, ...)

Arguments

obj

object to reformat.

...

not used. Only for compatibility between methods.

format

(rule) or (list) of rule depending on the class of obj.

string_as_fct

(flag) whether the reformatted character object should be converted to factor.

na_last

(flag) whether the level replacing NA should be last.

Note

When the rule is empty rule or when values subject to reformatting are absent from the object, no error is raised. The rest of the reformatting process (for instance the conversion to factor and the reformatting of factors levels if string_as_fct = TRUE) is still carried out.

Examples


# Reformatting of character.
obj <- c("a", "b", "x", NA)
attr(obj, "label") <- "my label"
format <- rule("A" = "a", "NN" = NA)

reformat(obj, format)
#> [1] A  b  x  NN
#> attr(,"label")
#> [1] my label
#> Levels: A b x NN

# Reformatting of factor.
obj <- factor(c("a", "aa", "b", "x", NA), levels = c("x", "b", "aa", "a", "z"))
attr(obj, "label") <- "my label"
format <- rule("A" = c("a", "aa"), "NN" = c(NA, "x"), "Not Present" = "z")

reformat(obj, format)
#> [1] A  A  b  NN NN
#> attr(,"label")
#> [1] my label
#> Levels: b A Not Present NN
reformat(obj, format, na_last = TRUE)
#> [1] A  A  b  NN NN
#> attr(,"label")
#> [1] my label
#> Levels: b A Not Present NN

# Reformatting of dm.
library(dm)

df1 <- data.frame(
  var1 = c("a", "b", NA),
  var2 = factor(c("F1", "F2", NA))
)

df2 <- data.frame(
  var1 = c("x", NA, "y"),
  var2 = factor(c("F11", NA, "F22"))
)

db <- dm(df1 = df1, df2 = df2)

format <- list(
  df1 = list(
    var1 = rule("X" = "x", "N" = NA)
  ),
  df2 = list(
    var1 = empty_rule,
    var2 = rule("f11" = "F11", "NN" = NA)
  )
)

reformat(db, format)
#> ── Metadata ────────────────────────────────────────────────────────────────────
#> Tables: `df1`, `df2`
#> Columns: 4
#> Primary keys: 0
#> Foreign keys: 0

# Reformatting of list of data.frame.
df1 <- data.frame(
  var1 = c("a", "b", NA),
  var2 = factor(c("F1", "F2", NA))
)

df2 <- data.frame(
  var1 = c("x", NA, "y"),
  var2 = factor(c("F11", NA, "F22"))
)

db <- list(df1 = df1, df2 = df2)

format <- list(
  df1 = list(
    var1 = rule("X" = "x", "N" = NA)
  ),
  df2 = list(
    var1 = empty_rule,
    var2 = rule("f11" = "F11", "NN" = NA)
  )
)

reformat(db, format)
#> $df1
#>   var1 var2
#> 1    a   F1
#> 2    b   F2
#> 3    N <NA>
#> 
#> $df2
#>   var1 var2
#> 1    x  f11
#> 2 <NA>   NN
#> 3    y  F22
#>