r语言 - 循环创建句子,反复向列表中添加额外的单词



我有一个df列,像这样:

tbody> <<tr>bc
value

使用tidyverse和for循环:

library(tidyverse)
df <- data.frame(V1 = c("a","b","c"))
for(i in 1:3){

print(paste("The values are",
df |> 
slice(1:i) |> 
pull(V1) |> 
str_c(collapse = " "),
"now."))
}

输出:

[1] "The values are a now."
[1] "The values are a b now."
[1] "The values are a b c now."

一个可能的解决方案:

library(tidyverse)
df %>% 
mutate(s = str_c("the values are ", 
accumulate(value, ~ str_c(.x, .y, sep = ", ")), " now.")) %>% 
pull(s)
#> [1] "the values are a now."       "the values are a, b now."   
#> [3] "the values are a, b, c now."

最新更新