[R] how to rename variables by lopping off first 3 characters

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Mon Mar 14 18:52:49 CET 2022


Hello,

I have already seen those names starting with 'i..' several times but I 
don't remember where nor why.
I think it has to do with encoding. Or maybe special characters. I have 
the impression that the best solution was to read the data in a way as 
to avoid the problem.

Using Bert's example data set, here are base R and tidyverse solutions.


dat <- data.frame(
   i..One = 1:3,
   i..Two = letters[1:3],
   ixx = 5:7)

# base R
names(dat) <- sub("^i\\.\\.", "", names(dat))
names(dat)

# tidyverse
dplyr::rename_with(dat, .fn = \(x) sub("^i\\.\\.", "", x), 
starts_with("i.."))


Hope this helps,

Rui Barradas

Às 16:26 de 14/03/2022, Christopher W Ryan via R-help escreveu:
> I have data coming to me from another source, in which some of the variable
> names begin with "i.."
> 
> As in "i..actual_meaningful_var_name"
> 
> I would like to remove the first three characters from any variable name if
> they are "i.."
> 
> I'm using R on Win 10 and dplyr, so ideally I'm looking for a dplyr
> solution. Apparently I'm just not understanding how the various select,
> contains, rename_at, rename_with, and so-on dplyr expressions work. I've
> tried various arrangements of them, usually resulting in
> 
> Error: `contains()` must be used within a *selecting* function.
> i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>
> 
> A simple select(contains(foo)) I can do fine, to select a subset of
> variables. It's combining it with renaming that I am struggling with.
> 
> Grateful for any advice.
> 
> Thanks.
> 
> --Chris Ryan
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list