Merge rows in one data.frame

前端 未结 1 1818
长发绾君心
长发绾君心 2021-01-25 20:06

This is a very similar question to merge-two-rows-in-one-dataframe but I have string variables and just want to collapse some rows that have the same country name. I adapted the

相关标签:
1条回答
  • 2021-01-25 20:59

    We could use data.table. We convert the 'data.frame' to 'data.table' (setDT(data)), grouped by 'name', we unlist the columns specified in the .SDcols, and paste it together.

    library(data.table)
    setDT(data)[, unlist(.SD), name, .SDcols=v1:v4][V1!='', paste(V1, collapse=', '), name]
    

    As the expected output is not showed, it could be also

    setDT(data)[, lapply(.SD, function(x) paste(x[x!=''], collapse='')) , name, .SDcols= v1:v4]
    

    Update

    Based on the expected output, we convert the 'factor' columns ('v1:v4') to 'character' class, then use the formula method of aggregate and paste the columns grouped by 'name'.

    data[3:6] <- lapply(data[3:6], as.character)
    aggregate(.~name, data[-1], FUN=function(x) paste(x[x!=''], collapse=', '))
    
    0 讨论(0)
提交回复
热议问题