2

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) 
2
  • In your case, Station are NOT row names. It is a separate column Commented Jul 15, 2020 at 21:23
  • Thanks @slava-kohut, i meant to change the unique row name under station column. Commented Jul 15, 2020 at 21:34

4 Answers 4

3

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"))) 
Sign up to request clarification or add additional context in comments.

Comments

0

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 

Comments

0

You can do it using case_when:

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

Comments

0

Another simple solution

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.