R言語学習ノート:glueパッケージ実現変数パラメータ

2148 ワード

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 %` %`
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 >$.",
     .open = "<>")
# The value of $e^{2\pi i}$ is $1$.

#                
`foo}\`` 

参照リンク:tidyverse/glue