r - 从数据框中提取值并将它们填充到 R 中的模板短语中
问题描述
给定如下数据集:
df <- structure(list(type = structure(c(2L, 3L, 1L), .Label = c("negative",
"positive", "zero"), class = "factor"), count = c(10L, 5L, 8L
), percent = c(43.5, 21.7, 34.8)), class = "data.frame", row.names = c(NA,
-3L))
出去:
我想将表中的值填充到模板短语中,如下所示:
2020年,我们有10
城市有positive
增长,覆盖43.5
所有城市的%;5
城市有zero
增长,21.7
占所有城市的百分比;8
城市有negative
增长,占21.7
所有城市的 %。
模板:
2020 年,我们有{}个城市有{}个增长,覆盖所有城市的{} %;{}个城市有{}个增长,覆盖所有城市的{} %;{}个城市有{ }个增长,覆盖所有城市的{} %。
我怎么能在 R 中做到这一点?
解决方案
paste0
您可以使用/创建一个简单的句子,sprintf
并使用数据框中的相应值更改占位符。
这是另一种不需要列出数据框中的每个单独值的方式。
string <- 'In 2020, we have %s cities have %s growth, which covers %s %% of all cities; %s cities have %s growth, which covers %s %% of all cities; and %s cities have %s growth, which covers %s %% of all cities'
do.call(sprintf, c(as.list(c(t(df[c(2, 1, 3)]))), fmt = string))
#[1] "In 2020, we have 10 cities have positive growth, which covers 43.5 % of all #cities; 5 cities have zero growth, which covers 21.7 % of all cities; and 8 #cities have negative growth, which covers 34.8 % of all cities"
df[c(2, 1, 3)]
用于对列重新排序,即count
第一列和type
第二列。这是必需的,因为您的句子始终具有count
价值 first, thentype
和 last percent
。c(t(df[c(2, 1, 3)]))
以行方式将数据框更改为向量,并sprintf
作为不同的参数传递给它。