首页 > 解决方案 > 将 stringr::str_glue 与管道一起使用

问题描述

我想str_glue与管道一起使用。我的代码:

library(tidyverse)

x <- c('john', 'bell', 'mary', 'cott')

x %>% 
  str_to_title(.) %>% 
  str_glue('Hi, {.}. How are you?')

但是,出现以下错误消息:

错误:所有未命名参数的长度必须为 1

期望输出:

Hi, John. How are you?
Hi, Bell. How are you?
Hi, Mary. How are you?
Hi, Cott. How are you?

标签: rstringr

解决方案


查看帮助help(str_glue),我想出了以下工作解决方案。您可以自己查看帮助。

x <- c('john', 'bell', 'mary', 'cott')
x <- data.frame(x)
rownames(x) <- x[,1]

x %>% 
str_glue_data("Hi, {rownames(.)}. How are you?")

#Hi, john. How are you?
#Hi, bell. How are you?
#Hi, mary. How are you?
#Hi, cott. How are you?

您也可以在str_glue不使用管道的情况下使用如下(我认为这不是您想要的,所以上面的数据框解决方法)

x <- c('john', 'bell', 'mary', 'cott')

str_glue('Hi, {x}. How are you?')
#Hi, john. How are you?
#Hi, bell. How are you?
#Hi, mary. How are you?
#Hi, cott. How are you?

希望有帮助。


推荐阅读