I looking for a way to efficiently apply a function to each row of data.table. Let\'s consider the following data table:
library(data.table)
library(stringr)
The most effective and idiomatic approach is to have a vectorized function.
In this case, some kind of regex
will do what you want
x[, V1 := gsub(" [[:alnum:]]*", "", b)]
a b V1
1: 1 12 13 12
2: 2 14 15 14
3: 3 16 17 16
4: 1 18 19 18
If you want to return the each split component, and you know there are two in each one, you can use Map
to coerce the result of strsplit
into the correct form
x[, c('b1','b2') := do.call(Map, c(f = c, strsplit(b, ' ')))]
x
a b b1 b2
1: 1 12 13 12 13
2: 2 14 15 14 15
3: 3 16 17 16 17
4: 1 18 19 18 19