Home > database >  Loop to create sentences which repeatedly add an extra word to a list
Loop to create sentences which repeatedly add an extra word to a list

Time:06-24

I have a df column like so:

value
a
b
c

I want to create a loop that produces 3 sentences of: 'The values are a now' 'The values are a b now' 'The values are a b c now'

I have created this loop:

    ##create loop for printing each sentence
for(i in 1:ncol(df)) { 
  
  #input individual values so that an additional value is added each time
  input = (paste(df$value[1:i]))
  
  #print 3 unique sentences with the loop
  print(paste('the values are', input, 'now'))

}

However, it prints separate sentences with each value e.g:

'The values are a now'

'The values are a now' 'The values are b now'

'The values are a now' 'The values are b now' 'The values are c now'

Any help would be great!

CodePudding user response:

Using tidyverse and a for loop:

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."))
}

Output:

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

CodePudding user response:

A possible solution:

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."
  • Related