2

I am trying to keep a data frame were I have a list of messages for the user. I'd like to be able to substitute my variables in my message with what is in the column i am referencing.

For example, this works:

df <- data.frame(id = rep(1:3, each = 3),
                 this = rep(letters[1:3], each = 3),
                 that = rep(letters[24:26], each = 3),
                 foo = rep(c("apple", "pear", "banana"), each = 3))

df %>% mutate(message = glue("{this} is {that}"))

But this does not:


library(tidyverse)
library(glue)

verbiage <- data.frame(id = 1:3,
                       message = c("{this} is {that}", "{foo} is something", "something is {foo}"))

verbiage

df <- data.frame(id = rep(1:3, each = 3),
                 this = rep(letters[1:3], each = 3),
                 that = rep(letters[24:26], each = 3),
                 foo = rep(c("apple", "pear", "banana"), each = 3))

df

df %>% 
  inner_join(verbiage, by = "id") %>% 
  mutate(message = glue(message))
Zoe
  • 27,060
  • 21
  • 118
  • 148
alexb523
  • 718
  • 2
  • 9
  • 26

1 Answers1

2

We can use rowwise

library(glue)
library(dplyr)
df %>% 
   inner_join(verbiage, by = "id")  %>%
   rowwise %>% 
   mutate(message = as.character(glue(as.character(message))))
# A tibble: 9 x 5
# Rowwise: 
#     id this  that  foo    message            
#  <int> <fct> <fct> <fct>  <chr>              
#1     1 a     x     apple  a is x             
#2     1 a     x     apple  a is x             
#3     1 a     x     apple  a is x             
#4     2 b     y     pear   pear is something  
#5     2 b     y     pear   pear is something  
#6     2 b     y     pear   pear is something  
#7     3 c     z     banana something is banana
#8     3 c     z     banana something is banana
#9     3 c     z     banana something is banana
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    thanks. i've never seen `rowwise` before i'll have to check that out. is the `as.character` needed around the `glue`? seems to be working fine without it. – alexb523 Mar 26 '20 at 23:15
  • @alexb523 In some versions, it breaks without `as.character` – akrun Mar 26 '20 at 23:16