[R] Matrix Operations

Wu Gong wg2f at mtmail.mtsu.edu
Sat Nov 27 18:51:46 CET 2010


Hi Romildo,

Merge two table by id2 first, then reshape to the wide format, sum by source
at last. Hope it helps.

### Data simulation
lsp.text <- " id source destiny     id2   caminho order
1  1      2       4          7       0     0
2  2      6      10          4       0     0
3  3      6       4          5       0     0
4  4      6       4          8       0     0 "
lsp <- read.table(textConnection(lsp.text),header=TRUE)
services.text <- "id2  bw prio pen fator order
1  1 128    5  32  0.25     0
2  2  64    5  16  0.25     0
3  3  64    5  64  1.00     0
4  4  16    5  16  1.00     0
5  5  32    1 192  6.00     0
6  6  64    1 512  8.00     0
7  7 512    3 128  0.25     0
8  8  32    7  32  1.00     0 "
services <- read.table(textConnection(services.text),header=TRUE)

## Delete unwanted columns and combine two table into one table by id2
mtraffic.1  <- merge(lsp[,c(2,3,4)],services[,c(1,2)],by="id2")

## Reshape table to wide style
library(reshape)
mtraffic.2 <- cast(mtraffic.1, source+id2 ~ destiny,fill=0)

## Sum by category(source)
colnames(mtraffic.2) <-
c(colnames(mtraffic.2)[1:2],paste("D",colnames(mtraffic.2)[-c(1:2)],sep=""))
mtraffic <- aggregate(. ~ source, data=mtraffic.2[,-2],FUN=sum)



-----
A R learner.
-- 
View this message in context: http://r.789695.n4.nabble.com/Matrix-Operations-tp3061550p3061773.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list