I'd like to change a column name in an intermediate step of a pipeline. Seems like I'm missing something simple.
I can do this:
library(dplyr)
library(purrr)
temp <- starwars[1:5,1:5]
temp <- set_names(temp,c("person",names(temp)[-1]))
This is what I want:
temp
#> # A tibble: 5 × 5
#> person height mass hair_color skin_color
#> <chr> <int> <dbl> <chr> <chr>
#> 1 Luke Skywalker 172 77 blond fair
#> 2 C-3PO 167 75 <NA> gold
#> 3 R2-D2 96 32 <NA> white, blue
#> 4 Darth Vader 202 136 none white
#> 5 Leia Organa 150 49 brown light
But I can't do this:
temp <- starwars[1:5,1:5] |>
set_names(c("person",names(~.)[-1]))
temp
#> # A tibble: 5 × 5
#> person person person person person
#> <chr> <int> <dbl> <chr> <chr>
#> 1 Luke Skywalker 172 77 blond fair
#> 2 C-3PO 167 75 <NA> gold
#> 3 R2-D2 96 32 <NA> white, blue
#> 4 Darth Vader 202 136 none white
#> 5 Leia Organa 150 49 brown light
Created on 2024-02-13 with reprex v2.1.0
Thanks.
You have already attached the dplyr
package so is there any reason rename_with
wouldn't work?
starwars[1:5,1:5] |>
rename_with(~ "Person", .cols = 1)
You can specify any tidy-select helper to pick the column. Here I selected the column by index.