I have a dataframe with columns id, feature_1, feature_2, feature_3 as follows.
df = data.frame(
id = sample(letters, 5),
feature_1 = sample(1:10, 5),
feature_2 = runif(5),
feature_3 = rnorm(5)
)
I want to rename all the feature columns by adding a prefix. The following line doesn't work and output error.
df %>%
rename_with(~(ifelse(names(.x) == "id", paste0("source_", names(.x)), "id")))
Error in names[cols] <- .fn(names[cols], ...) :
replacement has length zero
Any hint on how to modify this? What does .x represent inside rename_with? Thanks in advance!
library(dplyr)
df %>%
dplyr::rename_with(~ paste0("source_", .), -id)
The third argument to rename_with
is .cols
, where you can use tidyselect syntax to select the columns. Here -id
excludes this column.
Per the comments the .
syntax is a cleaner/simpler style than an writing an anonymous function, but you could accomplish this equivalently as:
df %>%
dplyr::rename_with(function(x) paste0("source_", x), -id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With