R語言學習筆記:glue包實現變量傳參


glue包介紹

glue包可用於自定義變量,然后通過傳參的方式,對字符串部分內容進行自適應修改。
例如:可將日期賦值為:date = as.Date("2019-12-05"),然后通過字符串拼接的形式,實現文件名稱自動更新,glue("The day is {date}."

具體用法


## glue包
## 功能:用於將變量傳入字符串並解釋變量

## 安裝
install.packages("glue")
devtools::install_github("tidyverse/glue")

## 使用
library(glue)
name <- "Hider"
glue('My name is {name}.')  ## My name is Hider.

## 多行長字符串也可以連接在一塊
name <- "Hider"
age <- 28
anniversary <- as.Date("1992-12-12")
glue('My name is {name},',
     ' my age next year is {age + 1},',
     ' my anniversary is {format(anniversary, "%A, %B %d, %Y")}.')
## My name is Hider, my age next year is 29, my anniversary is 星期六, 十二月 12, 1992.

## 可以把參數變量放到內部
glue('My name is {name},',
     ' my age next year is {age + 1},',
     ' my anniversary is {format(anniversary, "%A, %B %d, %Y")}.',
     name = "Hider",
     age = 28,
     anniversary = as.Date("1992-12-12"))
## My name is Hider, my age next year is 29, my anniversary is 星期六, 十二月 12, 1992.

library(tidyverse)
`%>%` <- magrittr::`%>%`
head(mtcars) %>% glue_data("{rownames(.)} has {hp} hp.")
# Mazda RX4 has 110 hp.
# Mazda RX4 Wag has 110 hp.
# Datsun 710 has 93 hp.
# Hornet 4 Drive has 110 hp.
# Hornet Sportabout has 175 hp.
# Valiant has 105 hp.

library(dplyr)
head(iris) %>%
  mutate(description = glue("This {Species} has a petal length of {Petal.Length}"))
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species                           description
# 1          5.1         3.5          1.4         0.2  setosa This setosa has a petal length of 1.4
# 2          4.9         3.0          1.4         0.2  setosa This setosa has a petal length of 1.4
# 3          4.7         3.2          1.3         0.2  setosa This setosa has a petal length of 1.3
# 4          4.6         3.1          1.5         0.2  setosa This setosa has a petal length of 1.5
# 5          5.0         3.6          1.4         0.2  setosa This setosa has a petal length of 1.4
# 6          5.4         3.9          1.7         0.4  setosa This setosa has a petal length of 1.7

## 前前后后的空行、空格會自動忽略
glue("
     A Formatted string
     Can have multiple lines
       with addititonal indention preserved.
     ")
# A Formatted string
# Can have multiple lines
# with addititonal indention preserved.

glue("
     
     leading or trailing newlines can be added explicitly
     
     ")
# leading or trailing newlines can be added explicitly

## 使用\\ 不換行
glue("
     A formatted string \\
     can also be on a \\
     single line.
     ")
# A formatted string can also be on a single line.

## 雙重大括號將不解釋變量
name <- "Hider"
glue("My name is {name}, not {{name}}.")
# My name is Hider, not {name}.

## 可以使用.open和.close指定替代分隔符
one <- "1"
glue("The value of $e^{2\\pi i}$ is $<<one>>$.",
     .open = "<<",
     .close = ">>")
# The value of $e^{2\pi i}$ is $1$.

# 有效的代碼都可以使用 雙反斜杠
`foo}\`` <- "foo"
glue("{
     {
     '}\\'' # { and } in comments, single quotes
     \"}\\\"\" # or double quotes are ignored
     `foo}\\`` # as are { in backticks
     }
     }")
# foo
# 真心看不懂。。

## glue_sql()構建SQL腳本
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
colnames(iris) <- gsub("[.]", "_", tolower(colnames(iris)))
DBI::dbWriteTable(con, "iris", iris)
# 這部分待數據庫配置好 再測試

## +號
y <- 1
y <- 5
glue("x + y") + " = {x + y}"
# x + y = 6
# x + y = 7
# x + y = 8
# x + y = 9
# x + y = 10
# 搞不懂 為什么會計算5次?

參考鏈接:tidyverse/glue


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM