Home > Software design >  Append text to a field based on another field's value
Append text to a field based on another field's value

Time:07-24

I want to append a text based on another field's value. For example:-

This is the current df:

field_x <- c("A", "A", "C", "B", "B", "C")
field_y <- c("Axl", "Slash", "Duff", "Steven", "Izzy", "Dizzy")

df <- cbind(field_x, field_y)

I need to change the field_y based on field_x values so that it looks like this:

field_x <- c("A", "A", "C", "B", "B", "C")
field_y <- c("Axl (Apple)", "Slash (Apple)", "Duff (Cat)", "Steven (Ball)", "Izzy (Ball)", "Dizzy (Cat)")

So, basically if field_x has "A" then "(Apple)" is to be appended to field_y and so forth. Thanks in advance!

CodePudding user response:

First note that your df is actually a matrix: when you cbind vectors, you get a matrix. So first thing to do is convert to dataframe. Then it depends on whether or not you are using dplyr.

field_x <- c("A", "A", "C", "B", "B", "C")
field_y <- c("Axl", "Slash", "Duff", "Steven", "Izzy", "Dizzy")
df <- cbind(field_x, field_y)
df <- as.data.frame(df)

Without dplyr:

df <- within(df, {
  s <- ifelse(field_x == "A", "Apple", ifelse(field_x == "B", "Ball", "Cat"))
  field_y <- paste0(field_y, "(", s, ")")
  rm(s)
})

With dplyr:

library(dplyr)
library(stringr)
library(magrittr)

df %<>%
  mutate(
    s = recode(field_x, "A" = "Apple", "B" = "Ball", "C" = "Cat"),
    field_y = str_glue("{field_y}({s})")) %>%
  select(-s)

Another way, with case_when instead of recode:

df %<>%
  mutate(
    s = case_when(
      field_x == "A" ~ "Apple",
      field_x == "B" ~ "Ball",
      field_x == "C" ~ "Cat"
    ),
    field_y = str_glue("{field_y}({s})")) %>%
  select(-s)

Note that I create an auxiliary variable s: it's not really necessary, but it makes the code more readable.

CodePudding user response:

Here is another approach: We could create a look-up table to address the concerns of @Tim Biegeleisen in the comment section:

look_up <- data.frame(x = c("A", "B" ,"C"),
           y = c("Apple", "Ball", "Cat"))


library(dplyr)
df %>% 
  as.data.frame() %>% 
  rowwise() %>%
  mutate(field_y = paste0(field_y, ' (', look_up$y[look_up$x==field_x], ')'))
  field_x field_y      
  <chr>   <chr>        
1 A       Axl (Apple)  
2 A       Slash (Apple)
3 C       Duff (Cat)   
4 B       Steven (Ball)
5 B       Izzy (Ball)  
6 C       Dizzy (Cat)  
  • Related