Applying a function to each row of a data.table

前端 未结 7 1295
日久生厌
日久生厌 2020-12-03 10:46

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)         


        
7条回答
  •  一整个雨季
    2020-12-03 11:11

    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
    

提交回复
热议问题