我有一个df列,像这样:
value | b |
---|
使用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."