[R] Merge rows

David Stevens david.stevens at usu.edu
Mon Jul 14 17:48:54 CEST 2014


Cautionary note on the solution below. Be sure the 'sndr' is either 
factor or character because, if sndr is numeric, as the list is 
populated, R will fill in non-adjacent list items with NULLs, leaving a 
list with many empty entries. So, the modified line is

       newdat[[as.character(vnam)]]<-newvec[-1]

David

On 7/12/2014 8:33 AM, David Stevens wrote:
> This is a (very) slightly modified version of Jim's reply that takes 
> the sender's email our of the list element and uses it as the name so 
> it can be accessed as newdat$'senders email' or newdat[['senders email']]
>
> newdat<-list()
> for(sndr in unique(rdvdf$sender)) {
>  newvec<-
>   as.character(unique(unlist(rdvdf[rdvdf$sender==sndr,])))
>  newdat[[(sndr)]]<-newvec[which(!is.na(newvec))][-1]
> }
>
> David
>
> On 7/12/2014 1:07 AM, Jim Lemon wrote:
>> On Fri, 11 Jul 2014 12:19:39 PM Ryan de Vera wrote:
>>> Hello all,
>>>
>>> I have a data frame filled with senders and recipients. Some of the
>> senders
>>> have multiple rows with different recipients and I want to merge
>> those
>>> rows. For example I have
>>>
>>> a at email.com     b at email.com
>>> a at email.com     c at email.com     d at email.com
>>> r at email.com      f at email.com
>>> r at email.com      h at email.com
>>>
>>> I want this to become
>>>
>>> a at email.com     b at email.com     c at email.com     d at email.com
>>> r at email.com      f at email.com      h at email.com
>>>
>>> How would I go about doing this?
>>>
>> Hi Ryan,
>> This is a bit messy, but assuming that you do have a data frame like
>> this:
>>
>> rdvdf<-
>> data.frame(sender=rep(c("a at email.com","r at email.com"),each=2),
>> recipient1=c("b at email.com","c at email.com","f at email.com","h at email.com"),
>>   recipient2=c(NA,"d at email.com",NA,NA))
>>
>> you can try this:
>>
>> newdat<-list()
>> senderno<-1
>> for(sndr in unique(rdvdf$sender)) {
>>   newvec<-
>>    as.character(unique(unlist(rdvdf[rdvdf$sender==sndr,])))
>>   newdat[[senderno]]<-newvec[!is.na(newvec)]
>>   senderno<-senderno+1
>> }
>>
>> Jim
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide 
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>

-- 
David K Stevens, P.E., Ph.D.
Professor and Head, Environmental Engineering
Civil and Environmental Engineering
Utah Water Research Laboratory
8200 Old Main Hill
Logan, UT  84322-8200
435 797 3229 - voice
435 797 1363 - fax
david.stevens at usu.edu



More information about the R-help mailing list