首页 > 解决方案 > 从数据框中提取值并将它们填充到 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 中做到这一点?

标签: rdplyr

解决方案


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 percentc(t(df[c(2, 1, 3)]))以行方式将数据框更改为向量,并sprintf作为不同的参数传递给它。


推荐阅读