dplyr rename "object not found"

Viewed 7466

When I try and rename multiple columns in dplyr, I'm getting an "object not found" error regarding the new name.

I am creating a new data frame using select, and then I'd like to change the names of columns 4:8.

commute_mode<-select(commute,geoid,GEO.id2,display_label,HD01_VD26,HD01_VD37,HD01_VD68,HD01_VD113,HD01_VD125) %>%
  rename(HD01_VD26 = drive, HD01_VD37 = carpool,HD01_VD68 = public_trans,HD01_VD113 = walk, HD01_VD125=bike_other)

but I'm getting

Error in .f(.x[[i]], ...) : object 'drive' not found
1 Answers

As has been pointed out in some comments, the new and old names of the variables need to be swapped in your select() function.

But as has also been noted, you can select AND rename your variables using select() by itself (rename() is best if you are keeping all the columns and only renaming certain ones). So instead of the unwieldy mydata %>% select(old_var1, old_var2) %>% rename (new_var1 = old_var1, new_var2 = old_var2), you simply have mydata %>% select(new_var1 = old_var1, new_var2 = old_var2). In your case, this would look like:

commute_mode <- commute %>% select(geoid, GEO.id2, display_label,
                                   drive = HD01_VD26, carpool = HD01_VD37,
                                   public_trans = HD01_VD68,
                                   walk = HD01_VD113,
                                   bike_other = HD01_VD125)

This is a great feature of the select() command, and it's always best to keep things as concise as possible!

For a more detailed explanation, you can check out https://dplyr.tidyverse.org/reference/select.html

Related