[R] copy the columns based on the code

Sarah Goslee sarah.goslee at gmail.com
Mon Mar 26 19:52:28 CEST 2012


Then there's something missing in what you tell us.


# this is an awkward and inefficient way of constructing a data frame
city<-data.frame(city="Barcelona",cod=1)
city<-rbind(city,data.frame(city="Madrid",cod=2))
city<-rbind(city,data.frame(city="Lisbon",cod=3))
city<-rbind(city,data.frame(city="Milan",cod=4))
city<-rbind(city,data.frame(city="London",cod=5))

travel<-data.frame(pos=1,Source=1,Destine=2)
travel<-rbind(travel,data.frame(pos=1,Source=1,Destine=3))
travel<-rbind(travel,data.frame(pos=2,Source=3,Destine=4))
travel<-rbind(travel,data.frame(pos=3,Source=2,Destine=4))
travel<-rbind(travel,data.frame(pos=4,Source=1,Destine=3))


temp <- merge(travel, city, by.x="Source", by.y="cod")
result <- merge(temp, city, by.x="Destine", by.y="cod")

> temp
  Source pos Destine      city
1      1   1       2 Barcelona
2      1   1       3 Barcelona
3      1   4       3 Barcelona
4      2   3       4    Madrid
5      3   2       4    Lisbon
> result
  Destine Source pos    city.x city.y
1       2      1   1 Barcelona Madrid
2       3      1   1 Barcelona Lisbon
3       3      1   4 Barcelona Lisbon
4       4      2   3    Madrid  Milan
5       4      3   2    Lisbon  Milan

On Mon, Mar 26, 2012 at 11:08 AM, MSousa <ricardosousa2000 at clix.pt> wrote:
> thanks for the reply,
>
>   But does not the results I need. What is confusing is that when making
> the first merge it gives only two cities when it should take three
>
>
> travel<-data.frame(pos=1,Source=1,Destine=2)
> travel<-rbind(travel,data.frame(pos=1,*Source=1*,Destine=3))
> travel<-rbind(travel,data.frame(pos=2,*Source=3*,Destine=4))
> travel<-rbind(travel,data.frame(pos=3,*Source=2*,Destine=4))
> travel<-rbind(travel,data.frame(pos=4,*Source=1*,Destine=3))
>
> temp1 <- merge(travel, city, by.x='Source', by.y='cod')
>>temp1  ()
> Source pos Destine      city
> 1      *1*   1       2 Barcelona
> 2      1   1       3 Barcelona
> 3      1   4       3 Barcelona
> 4      *2 *  3       4    Madrid
>

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list