5

My data looks like this:

#>           Artist          Album Year
#> 1        Beatles  Sgt. Pepper's 1967
#> 2 Rolling Stones Sticky Fingers 1971

And my question should be quite simple. I'm trying to use rename_if to prefix only the columns that start with the letter "A". So my desired output is:

#>       df1_Artist      df1_Album Year
#> 1        Beatles  Sgt. Pepper's 1967
#> 2 Rolling Stones Sticky Fingers 1971

You can see that "Year" should not be prefixed.

This is my attempt, but it's not quite working. Am I using starts_with incorrectly? Should I try break it into two lines so I can understand it more clearly? The purrr style functions I'm still learning, so it's not always intuitive to me yet.

df1 %>% rename_if(starts_with("A"), .funs = ~ paste0(df1, .))
#> Error in df1 %>% rename_if(starts_with("A"), .funs = ~paste0(df1, .)): could not find function "%>%"

Code for data input:

df1 <- data.frame(stringsAsFactors=FALSE,
      Artist = c("Beatles", "Rolling Stones"),
       Album = c("Sgt. Pepper's", "Sticky Fingers"),
        Year = c(1967, 1971)
)
Jeremy K.
  • 1,710
  • 14
  • 35

2 Answers2

10

rename_if expects a logical vector as predicate function. starts_with selects variables based on their name. Use base startsWith instead which returns a logical vector based on prefix

library(dplyr)
df1 %>% rename_if(startsWith(names(.), "A"), ~paste0("df1_", .))

#      df1_Artist      df1_Album Year
#1        Beatles  Sgt. Pepper's 1967
#2 Rolling Stones Sticky Fingers 1971

Or if you want to stay in tidyverse you can also use str_detect

df1 %>% rename_if(stringr::str_detect(names(.), "^A"), ~paste0("df1_", .))

To use starts_with we can use rename_at which has vars argument.

df1 %>% rename_at(vars(starts_with("A")), ~paste0("df1_", .))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    This edit is very helpful in explaining the difference between `rename_at` and `rename_if` to me. I'd never understood the difference before. Thank you. – Jeremy K. Jun 21 '19 at 02:52
  • By the way, do you recommend any particular source for me to learn things like `rename_at` and `rename_if` and purrr functions? Would Hadley's R4DS be the best thing for me to work through? – Jeremy K. Jun 21 '19 at 03:13
  • 3
    @RAndStata Unfortunately, I'll not be the best person to answer that because I haven't read much of the resources online. My knowledge mostly comes from reading other people's answers here and checking documentation of functions while trying to answer questions. – Ronak Shah Jun 21 '19 at 03:19
4

We can use

library(tidyverse)
df1 %>%
  rename_at(vars(starts_with("A")), ~ str_c("df1_", .))
#     df1_Artist      df1_Album Year
#1        Beatles  Sgt. Pepper's 1967
#2 Rolling Stones Sticky Fingers 1971
akrun
  • 874,273
  • 37
  • 540
  • 662