gpt4 book ai didi

r - 从数据框中提取值并将其填充到 R 中的模板短语中

转载 作者:行者123 更新时间:2023-12-02 18:54:26 24 4
gpt4 key购买 nike

给定一个数据集如下:

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))

输出:

enter image description here

我想将表中的值填充到模板短语中,如下所示:

2020年,我们有10个城市实现增长,占所有城市的43.5%; 5 个城市的增长,占所有城市的21.7%;和 8 个城市出现增长,占所有城市的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 值,然后是 type,最后是 percentc(t(df[c(2, 1, 3)])) 以行方式将数据帧更改为向量,并将其作为不同的参数传递给 sprintf .

关于r - 从数据框中提取值并将其填充到 R 中的模板短语中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66348541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com