R collapse multiple rows into 1 row - same columns

后端 未结 3 530
清歌不尽
清歌不尽 2020-12-18 07:18

This is piggy backing on a question I answered last night as I am reconsidering how I\'d like to format my data. I did search but couldn\'t find up with any applicable answe

3条回答
  •  青春惊慌失措
    2020-12-18 07:55

    As you suggested that you would like a data.table solution in your comment, you could use

    library(data.table)
    df <- data.table(record_numb,col_a,col_b,col_c)
    
    df[, lapply(.SD, paste0, collapse=""), by=record_numb]
       record_numb col_a col_b col_c
    1:           1   123   234   543
    2:           2   987   765   543
    

    .SD basically says, "take all the variables in my data.table" except those in the by argument. In @Frank's answer, he reduces the set of the variables using .SDcols. If you want to cast the variables into numeric, you can still do this in one line. Here is a chaining method.

    df[, lapply(.SD, paste0, collapse=""), by=record_numb][, lapply(.SD, as.integer)]
    

    The second "chain" casts all the variables as integers.

提交回复
热议问题