[Rd] eval(parse()) within mutate() returning same value for all rows

Dirk Eddelbuettel edd @end|ng |rom deb|@n@org
Sat Dec 30 00:14:30 CET 2023


On 29 December 2023 at 22:31, Mateo Obregón wrote:
| Thanks Gabor, I like your solution that splits the args into separate columns, 
| in turn making the sprintf() call more interpretable .

Well you may also like `tstrsplit()`, a gem inside data.table:

> suppressMessages(library(data.table))
>
> D <- data.table(words="%s plus %s equals %s", args=c("1,1,2", "2,2,4", "3,3,6"))
> D
                  words   args
                 <char> <char>
1: %s plus %s equals %s  1,1,2
2: %s plus %s equals %s  2,2,4
3: %s plus %s equals %s  3,3,6
>
> D[, c('a','b','c') := tstrsplit(args, ",")]
> D
                  words   args      a      b      c
                 <char> <char> <char> <char> <char>
1: %s plus %s equals %s  1,1,2      1      1      2
2: %s plus %s equals %s  2,2,4      2      2      4
3: %s plus %s equals %s  3,3,6      3      3      6
>
> D[, res := sprintf(words, a, b, c)]
> D
                  words   args      a      b      c               res
                 <char> <char> <char> <char> <char>            <char>
1: %s plus %s equals %s  1,1,2      1      1      2 1 plus 1 equals 2
2: %s plus %s equals %s  2,2,4      2      2      4 2 plus 2 equals 4
3: %s plus %s equals %s  3,3,6      3      3      6 3 plus 3 equals 6
> 

so all we do here is a one-liner in data.table if you're so inclined:


> D <- data.table(words="%s plus %s equals %s", args=c("1,1,2", "2,2,4", "3,3,6"))
> D[, c('a','b','c') := tstrsplit(args, ",")][, res := sprintf(words, a, b, c)][, .(res)]
                 res
              <char>
1: 1 plus 1 equals 2
2: 2 plus 2 equals 4
3: 3 plus 3 equals 6
> 

data.table is very powerful and expressive. It is much worth getting into
which I really only did ten or so years into using R.

Dirk

-- 
dirk.eddelbuettel.com | @eddelbuettel | edd using debian.org



More information about the R-devel mailing list