How to format strings using values from other column in R

Viewed 287

I need to do some string formatting using values from other column which separated by commas. Let's say I have a data frame like this:

words <- c('%s + %s equal %s', '%s + %s equal %s')
arguments <- c('1,1,2', '2,2,4')
df <- data.frame(words, arguments)
df
             words    arguments
1 %s + %s equal %s        1,1,2
2 %s + %s equal %s        2,2,4

And I need a result like this:

             words    arguments         combined
1 %s + %s equal %s        1,1,2    1 + 1 equal 2
2 %s + %s equal %s        2,2,4    2 + 2 equal 4

Any idea how can I do that?

3 Answers

The words column is well suited for sprintf. Try the following :

df$combined <- apply(df, 1, function(x) do.call(sprintf, 
                       c(as.list(strsplit(x[2], ',')[[1]]), fmt = x[[1]])))
df

#             words arguments      combined
#1 %s + %s equal %s     1,1,2 1 + 1 equal 2
#2 %s + %s equal %s     2,2,4 2 + 2 equal 4

We split the arguments values on ",", use do.call to pass them as separate arguments of sprintf and create the combined string. x[2] in apply refers to arguments column whereas x[1] is for words column.

With dplyr:

library(dplyr)
df %>% mutate(combined = eval(parse(text = sprintf("sprintf('%s', %s)", words, arguments))))
             words arguments      combined
1 %s + %s equal %s     1,1,2 1 + 1 equal 2
2 %s + %s equal %s     2,2,4 2 + 2 equal 4

With base R:

df$combined <- apply(df, 1, function(x) eval(parse(text = sprintf("sprintf('%s', %s)", x[1], x[2]))))
df
             words arguments      combined
1 %s + %s equal %s     1,1,2 1 + 1 equal 2
2 %s + %s equal %s     2,2,4 2 + 2 equal 4

Very similar to Ronak's solution but using some data.table and purrr for concision:

library(purrr)
library(data.table)

df$combind <- map_chr(
  seq_len(nrow(df)), 
  ~do.call(sprintf, c(fmt = df$words[.], tstrsplit(df$arguments[.], ",")))
)

#              words arguments       combind
# 1 %s + %s equal %s     1,1,2 1 + 1 equal 2
# 2 %s + %s equal %s     2,2,4 2 + 2 equal 4
Related