Get / Set a variable label
var_label(x, unlist = FALSE) var_label(x) <- value set_variable_labels(.data, ..., .labels = NA)
| x | an object |
|---|---|
| unlist | for data frames, return a named vector instead of a list |
| value | a character string or |
| .data | a data frame |
| ... | name-value pairs of variable labels (see examples) |
| .labels | variable labels to be applied to the data.frame,
using the same syntax as |
set_variable_labels will return an updated copy of .data.
For data frames, if value is a named list, only elements whose name will
match a column of the data frame will be taken into account. If value
is a character vector, labels should in the same order as the columns of the
data.frame.
set_variable_labels could be used with dplyr.
var_label(iris$Sepal.Length)#> NULLvar_label(iris$Sepal.Length) <- 'Length of the sepal'# NOT RUN { View(iris) # }# To remove a variable label var_label(iris$Sepal.Length) <- NULL # To change several variable labels at once var_label(iris) <- c( "sepal length", "sepal width", "petal length", "petal width", "species" ) var_label(iris)#> $Sepal.Length #> [1] "sepal length" #> #> $Sepal.Width #> [1] "sepal width" #> #> $Petal.Length #> [1] "petal length" #> #> $Petal.Width #> [1] "petal width" #> #> $Species #> [1] "species" #>var_label(iris) <- list( Petal.Width = "width of the petal", Petal.Length = "length of the petal" ) var_label(iris)#> $Sepal.Length #> [1] "sepal length" #> #> $Sepal.Width #> [1] "sepal width" #> #> $Petal.Length #> [1] "length of the petal" #> #> $Petal.Width #> [1] "width of the petal" #> #> $Species #> [1] "species" #>var_label(iris, unlist = TRUE)#> Sepal.Length Sepal.Width Petal.Length #> "sepal length" "sepal width" "length of the petal" #> Petal.Width Species #> "width of the petal" "species"if (require(dplyr)) { # adding some variable labels df <- data_frame(s1 = c("M", "M", "F"), s2 = c(1, 1, 2)) %>% set_variable_labels(s1 = "Sex", s2 = "Yes or No?") var_label(df) # removing a variable label df <- df %>% set_variable_labels(s2 = NULL) var_label(df$s2) # defining variable labels derived from variable names if (require(snakecase)) { iris <- iris %>% set_variable_labels(.labels = to_sentence_case(names(iris))) var_label(iris) } }#>#> $Sepal.Length #> [1] "Sepal length" #> #> $Sepal.Width #> [1] "Sepal width" #> #> $Petal.Length #> [1] "Petal length" #> #> $Petal.Width #> [1] "Petal width" #> #> $Species #> [1] "Species" #>