R collapse multiple rows into 1 row - same columns

后端 未结 3 531
清歌不尽
清歌不尽 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:38

    You can reshape to long format, drop the blank entries and then go back to wide:

    res <- dcast(melt(df, id.vars = "record_numb")[ value != "" ], record_numb ~ variable)
    
       record_numb col_a col_b col_c
    1:           1   123   234   543
    2:           2   987   765   543
    

    You may find it more readable at first using magrittr:

    library(magrittr)
    res = df %>% 
      melt(id.vars = "record_numb") %>% 
      .[ value != "" ] %>% 
      dcast(record_numb ~ variable)
    

    The numbers are still formatted as strings, but you can convert them with...

    cols = setdiff(names(res), "record_numb")
    res[, (cols) := lapply(.SD, type.convert), .SDcols = cols]
    

    Type conversion will change each column to whatever class it looks like it should be (numeric, integer, whatever). See ?type.convert.

提交回复
热议问题