Apply a function to a subset of data.table columns, by column-indices instead of name

前端 未结 1 1203
无人共我
无人共我 2020-11-30 23:57

I\'m trying to apply a function to a group of columns in a large data.table without referring to each one individually.

a <- data.table(
  a=as.character(         


        
相关标签:
1条回答
  • 2020-12-01 00:54

    The idiomatic approach is to use .SD and .SDcols

    You can force the RHS to be evaluated in the parent frame by wrapping in ()

    a[, (b) := lapply(.SD, as.numeric), .SDcols = b]
    

    For columns 2:3

    a[, 2:3 := lapply(.SD, as.numeric), .SDcols = 2:3]
    

    or

    mysubset <- 2:3
    a[, (mysubset) := lapply(.SD, as.numeric), .SDcols = mysubset]
    
    0 讨论(0)
提交回复
热议问题