Advanced R Tutorial - Use SDcols In data.table

Advanced R Tutorial – Use SDcols In data.table

Outline

    Original Post

    Advanced R Tutorial – Use SDcols In data.table


    SDcols is an useful but tricky method in data.table. The statement of it is hard to remember, so I wrote down some examples, copying and pasting when I need them.

    Use lapply with .SDcols

    cols <- c('COL1', 'COL2', 'COL3')
    
    main_tb <- main_tb %>% 
      .[,  c(cols):= lapply(.SD, function(x) ifelse(is.na(x), 0, x))
        , .SDcols = cols]

    Aggregate with .SDcols

    cols_by <- c('COL1', 'COL2')
    cols_sum <- c('COL3', 'COL4')
    
    dt <- dt %>%
      .[, lapply(.SD, sum), by = item_no_col, .SDcols = cols_sum]

    Recommended Posts

    Learn Python And R In DataCamp. Start Your Data Science Career.



    Related Posts

    Aron

    A data scientist working in a retail company, with experience in web design and marketing. Recently dives into cryptocurrency and quantitative investing.

    facebook telegram
    Content Protection by DMCA.com

    Leave a Reply

    • Required fields are market * .
    • Your email address will not be published.
    • Please ensure your email address is correct, then you will get a notification once a new comment reply.

    Your email address will not be published. Required fields are marked *