[R] Rename variables starting with digits
Bert Gunter
bgunter@4567 @end|ng |rom gm@||@com
Tue Oct 5 19:21:38 CEST 2021
... and to add to what Eric and Duncan have said, what you have as column
names depends on how the data were imported. e.g.:
> d1 <-data.frame(a = 1:3, `1b` = letters[1:3]) ## check.names has a
default of TRUE
> names(d1)
[1] "a" "X1b" ## note the conversion to a syntactically valid name. See
?data.frame and ?make.names for details
> d2 <-data.frame(a = 1:3, `1b` = letters[1:3], check.names = FALSE)
> names(d2)
[1] "a" "1b"
So what does names(behavioral_df) give?
Bert Gunter
"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Tue, Oct 5, 2021 at 10:11 AM Duncan Murdoch <murdoch.duncan using gmail.com>
wrote:
> On 04/10/2021 2:02 p.m., Anne Zach 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'))
> >
> > ```
>
> You should also consider not renaming the columns. R allows
> non-standard names to be used as long as you quote them somehow. For
> example,
>
> behavioral_df[, "50%"]
>
> will get you the column with name "50%", as will
>
> behavioral_df$`50%`
>
> I suspect most tidyverse functions will be fine with the `50%` style of
> quoting.
>
> Duncan Murdoch
>
> ______________________________________________
> 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list