@@ -145,11 +145,13 @@ remove_reserved_variable_names <- function(variables, reserved) {
145
145
146
146
# ' Set variable names in `draws` objects
147
147
# '
148
- # ' Set variable names for all variables in a [`draws`] object. Useful
149
- # ' when using pipe operators.
148
+ # ' Set variable names for all variables in a [`draws`] object. Useful when using
149
+ # ' pipe operators. The additional helper function `repair_variable_names()` can
150
+ # ' convert variable names using periods (e.g. `"theta.1"`) to the more common
151
+ # ' square brackets (`"theta[1]"`) that are better supported by the package.
150
152
# '
151
153
# ' @param x (draws) A [`draws`] object.
152
- # ' @param variables (character) new variable names.
154
+ # ' @param variables (character) New variable names.
153
155
# ' @template args-methods-dots
154
156
# '
155
157
# ' @return Returns a [`draws`] object of the same format as `x`, with
@@ -173,6 +175,31 @@ set_variables <- function(x, variables, ...) {
173
175
return (x )
174
176
}
175
177
178
+ # ' @rdname set_variables
179
+ # ' @param old_variables (character) Variable names to repair. Should be variable
180
+ # ' names with periods to convert to square brackets (e.g., `"theta.1"` ->
181
+ # ' `"theta[1]"`, `"theta.1.1"` -> `"theta[1,1]"`).
182
+ # ' @examples
183
+ # ' # using repair_variable_names
184
+ # ' x <- matrix(rnorm(100), ncol = 2)
185
+ # ' colnames(x) <- c("theta.1", "theta.2")
186
+ # ' repair_variable_names(colnames(x))
187
+ # ' x <- set_variables(as_draws(x), repair_variable_names(colnames(x)))
188
+ # ' variables(x)
189
+ # '
190
+ # ' @export
191
+ repair_variable_names <- function (old_variables ) {
192
+ if (! all(grepl(" \\ ." , old_variables ))) {
193
+ stop_no_call(
194
+ " All names in 'old_variables' must contain at least one '.' in the name."
195
+ )
196
+ }
197
+ repaired_variables <- sub(" \\ ." , " [" , old_variables )
198
+ repaired_variables <- gsub(" \\ ." , " ," , repaired_variables )
199
+ repaired_variables [grep(" \\ [" , repaired_variables )] <-
200
+ paste0(repaired_variables [grep(" \\ [" , repaired_variables )], " ]" )
201
+ repaired_variables
202
+ }
176
203
177
204
# ' @rdname draws-index
178
205
# ' @export
0 commit comments