【问题标题】:r - use `glue` to substitute variables in a column with whats in another columnr - 使用 `glue` 将列中的变量替换为另一列中的变量
【发布时间】:2020-07-07 16:03:11
【问题描述】:

如果我有给用户的消息列表,我正在尝试保留一个数据框。我希望能够用我正在引用的列中的内容替换我的消息中的变量。

例如,这是有效的:

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}"))

但这不是:


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))

【问题讨论】:

    标签: r tidyverse r-glue


    【解决方案1】:

    我们可以使用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
    

    【讨论】:

    • 谢谢。在我必须检查之前,我从未见过rowwiseglue 周围是否需要 as.character?没有它似乎工作正常。
    • @alexb523 在某些版本中,它会在没有as.character的情况下中断
    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 2019-11-01
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多