Iterating a Data Frame to Create Strings

I frequently find myself wanting to iterate over a data frame to output a English sentence for each item. This often take the form of what becomes a long and frequently complex paste0() operation. It becomes complex because the grammar of that sentence is affected by the value in the variables.

As a simple example, inside the paste0() I might embed an ifelse() to account for pluralization. If some value X is zero I might add "no objects" to the sentence but if X is one, I would want "one object" added to the string and it's more than one, I'd want str(x) + " objects" appended.

Every time I go through this process the resulting code seems unwieldy and inelegant. It makes me think there's likely a better way to go.

If this all makes sense to you, I'd value any advice.

Thanks!

Take a look at glue :package:. It definitely will reduce a bit of mess, but I'm not sure there is any way to do it elegantly. You can also try to see the repeating patterns and put them into functions to see if that simplifies things a bit.

1 Like

Thank you, Misha. I'll have a look. Appreciate the note.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.