Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Idea: implement set_var_labels_with #163

Closed
ABohynDOE opened this issue Oct 2, 2024 · 2 comments · Fixed by #164
Closed

Idea: implement set_var_labels_with #163

ABohynDOE opened this issue Oct 2, 2024 · 2 comments · Fixed by #164

Comments

@ABohynDOE
Copy link

Firstly, I really enjoy this package ! I mainly use the set_var_labels() function to define variable labels to obtain nice summary tables with gtsummary.

However, I often think that it would be useful to have a function that sets variable labels based on the column names and that can be applied in the same way as rename_with() works.

For example, if I have a data frame with columns quest_1 to quest_10, and location_A to location_Z, I wish there was a function I could use to do:

labelled_df <- df %>%
  set_var_labels_with(
    .fn = ~paste0("Question ", str_extract(.x, "\\d+$")),
    .cols = starts_with("quest_")
  ) %>% 
  set_var_labels_with(
    .fn = ~paste0("Location ", str_extract(.x, ".$")),
    .cols = starts_with("location_")
  )

Of course this is maybe a silly example, but I think that it could allow labelling variables within a pipe workflow, without having to manually generate labels when there are many columns.

@larmarange
Copy link
Owner

larmarange commented Oct 3, 2024

There is already an update_variable_labels_with() function provided by labelled. With #164, variable names are now accessible using names().

library(labelled)

iris |> 
  update_variable_labels_with(~ toupper(names(.x))) |> 
  look_for()
#>  pos variable     label        col_type missing values    
#>  1   Sepal.Length SEPAL.LENGTH dbl      0                 
#>  2   Sepal.Width  SEPAL.WIDTH  dbl      0                 
#>  3   Petal.Length PETAL.LENGTH dbl      0                 
#>  4   Petal.Width  PETAL.WIDTH  dbl      0                 
#>  5   Species      SPECIES      fct      0       setosa    
#>                                                 versicolor
#>                                                 virginica

Created on 2024-10-03 with reprex v2.1.1

@ABohynDOE
Copy link
Author

OK thanks a lot, I didn't find this function earlier !

larmarange added a commit that referenced this issue Oct 3, 2024
…variable name (#164)

* in `update_variable_labels_with()`, it is now possible to access the variable
  name inside `.fn` by using `names()`

fix #163

* update workflows

* additional tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants