How to change the row names in R data.frame?

Viewed 3907

I would like to rename station in DF to something like DA056 to Happy and AB786 to Sad.

library(tidyverse)

DF1 <- data.frame(Station = rep("DA056",3), Level = 100:102) 
DF2 <- data.frame(Station = rep("AB786",3), Level = 201:203) 
DF <- bind_rows(DF1,DF2)
4 Answers

We can use factor with labels specified for corresponding levels

library(dplyr)
DF <- DF %>%
    mutate(Station = factor(Station, levels = c("DA056", "AB786"), 
              labels = c("Happy", "Sad")))

DF$Station
#[1] Happy Happy Happy Sad   Sad   Sad  
#Levels: Happy Sad

Or with recode

DF %>%
     mutate(Station = recode(Station, DA056 = 'Happy', AB786 = 'Sad'))
#  Station Level
#1   Happy   100
#2   Happy   101
#3   Happy   102
#4     Sad   201
#5     Sad   202
#6     Sad   203

If there are many values to be changed, a better option is a join after creating a key/val dataset

keyval <- data.frame(Station = c("DA056", "AB786"),
    val = c("Happy", "Sad"), stringsAsFactors = FALSE)
DF %>%
     left_join(keyval) %>%
     mutate(Station = coalesce(val, Station))

Or with base R

DF$Station <- with(df,  factor(Station, levels = c("DA056", "AB786"), 
              labels = c("Happy", "Sad")))

An option is to use dplyr::case_when:

library(dplyr)
DF1 <- data.frame(Station = rep("DA056",3), Level = 100:102, stringsAsFactors = F) 
DF2 <- data.frame(Station = rep("AB786",3), Level = 201:203, stringsAsFactors = F) 
DF <- bind_rows(DF1,DF2)

DF <- DF %>% mutate(Station = case_when( Station == "DA056" ~ "Happy",
                                         Station == "AB786" ~ "Sad",
                                         TRUE ~ Station))

Output

> DF
  Station Level
1   Happy   100
2   Happy   101
3   Happy   102
4     Sad   201
5     Sad   202
6     Sad   203

You can do it using case_when:

DF %>%
  mutate(Station = case_when(Station == "DA056"  ~ "Happy", Station =="AB786" ~ "Sad"))

Another simple solution

DF$Station = ifelse(DF$Station == "DA056", "Happy", "Sad")
Related