[R] Rename variables starting with digits

Jim Lemon drj|m|emon @end|ng |rom gm@||@com
Wed Oct 6 00:12:13 CEST 2021


Hi Anne,
As mentioned above, you may have to do nothing. Here is an example
that might clarify that:

azdat<-read.table(text="subject 1 2 3
1 10 20 30
2 11 22 33",
header=TRUE,stringsAsFactors=FALSE)
azdat
 subject X1 X2 X3
1       1 10 20 30
2       2 11 22 33

As you can see, R simply prepends an "X" to numeric names. If you
really want a "v":

names(azdat)<-gsub("X","v",names(azdat))

Jim
Always happy to help an ANZAC (bad joke)

On Wed, Oct 6, 2021 at 3:15 AM Anne Zach <anne.zach.zach using gmail.com> wrote:
>
> Dear R users,
>
> I have a dataframe that contains several variables, among which 105
> correspond to scores on certain trials. Unfortunately, when I imported this
> dataframe into R, I realised that the variable names corresponding to each
> trial begin with digits, which violates R naming conventions.
>
> I am trying to relabel these variables by adding a 'v' as a prefix to each
> of them, I'd like to use tidyverse, but I am struggling with this process
> of renaming. When I run this chunk of code, no error occurs but my
> variables are not renamed. I'm fairly new to R and I can't understand what
> I'm doing wrong.
>
> ```{r}
>
> behavioral_df <- behavioral_df %>% rename_with(.fn =  ~paste0("v"),
> starts_with('^\\d'))
>
> ```
>
> I appreciate if you can help.
>
> Best,
> Anne
>
>         [[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