mercredi 24 mars 2021

dplyr::rename() if condition about column contents is met

Say I wanted to rename a column based on the condition that the contents of the column contain a specific value.

For example, if iris$Species contains "virginica", rename to Species to flower.name, else keep the name as Species.

This code works:

library(dplyr)
iris <- if("virginica" %in% iris$Species){
  rename(iris, flower.name = Species)
}
iris %>% names

but I was hoping their was a more elegant dplyr way of doing this with one of the existing functions, such as rename_if()?

Aucun commentaire:

Enregistrer un commentaire