Applying a function to each row of a data.table

前端 未结 7 1296
日久生厌
日久生厌 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:04

    How about :

    x
       a     b
    1: 1 12 13
    2: 2 14 15
    3: 3 16 17
    4: 1 18 19
    
    x[,list(a=rep(a,each=2), V1=unlist(strsplit(b," ")))]
       a V1
    1: 1 12
    2: 1 13
    3: 2 14
    4: 2 15
    5: 3 16
    6: 3 17
    7: 1 18
    8: 1 19
    

    Generalized solution given comment :

    x[,{s=strsplit(b," ");list(a=rep(a,sapply(s,length)), V1=unlist(s))}]
    

提交回复
热议问题