在一个data.frame中合并行 [英] Merge rows in one data.frame

查看:68
本文介绍了在一个data.frame中合并行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与 merge-两行合一数据帧,但是我有字符串变量,只想折叠一些具有相同国家名称的行.我改编了MWER

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 MWER

data<-data.frame(code= c(345, 346), name= "Yemen", v1= c("", "text1"), v2= c("text2", ""),v3= c("text3", ""),v4= c("", "text4"))
code  name    v1    v2    v3    v4
345   Yemen         text2 text3      
346   Yemen   text1             text4

aggregate(x=data[c("v1","v2","v3","v4")], by=list(name=data$name), paste)
name v1.1  v1.2  v2.1 v2.2  v3.1 v3.2 v4.1  v4.2
1 Yemen      text1 text2      text3           text4

我希望粘贴可以作为将empthy单元格与另一行文本结合使用的函数,但是我不知何故获得了带有更多变量v1.1的一行,依此类推.

I was hoping paste would work as a function to combine the empthy cell with the text of the other row, but I somehow get one row with more variables v1.1 and so on.

推荐答案

我们可以使用data.table.我们将'data.frame'转换为'data.table'(setDT(data)),按'name'分组,我们unlist.SDcols中指定的列,然后将paste在一起.

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]

更新

根据预期的输出,我们将'factor'列('v1:v4')转换为'character'类,然后使用aggregatepaste按'name'分组的列的公式方法.

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=', '))

这篇关于在一个data.frame中合并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆