Skip to content

rename_with() doesn't handle factors well #6561

Description

@jmbarbone

rename_with.data.frame() has unexpected results when .fn returns a factor -- or at least unexpected for me. Documentation does suggest that .fn should return a character vector, but I wouldn't expect factors to be coerced to integers first.

The coercion occurs within [<-, which could be replaced with vec_slice()?

names[cols] <- .fn(names[cols], ...)

df <- data.frame(
  a = 1,
  b = 2,
  c = 3
)

foo <- function(x) {
  factor(toupper(x))
}

dplyr::rename_with(df, foo)
#>   1 2 3
#> 1 1 2 3


# name reassignment within rename_with.data.frame()
x <- c("a", "b", "c")
x[1:3] <- foo(x)
x
#> [1] "1" "2" "3"


# vctrs seems fine
x <- c("a", "b", "c")
vctrs::vec_slice(x, 2:3) <- foo(x[2:3])
x
#> [1] "a" "B" "C"

Created on 2022-11-23 with reprex v2.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions