Summer Gleek
Summer Gleek

Reputation: 344

adding elements with same name in a matrix

I have two matrices

Mdates<-c("8Q1","8Q2","8Q3","8Q4","9Q1","9Q2","9Q3","9Q4","10Q1","10Q2","10Q3","10Q4","11Q1","11Q2","11Q3","11Q4","12Q1","12Q2","12Q3","12Q4","13Q1","13Q2","13Q3","14Q1","14Q2")
Cr<-matrix(c("14Q2","13Q2","14Q2","14Q1","13Q4","13Q4","12Q4","13Q3","13Q4","12Q3","14Q2",12867.8,12710.7,10746.9,9634.4,8238.5,7835.2,7315.6,7263.1,7002.7,6104.8,5759.3),ncol=2,byrow=FALSE)

I add all the things with the same name in Cr and put it under the same column name in Mdates, so idealy it would look like this:

8Q1 8Q2 8Q3 8Q4 9Q1 9Q2 9Q3 9Q4 10Q1 10Q2 10Q3 10Q4 11Q1 11Q2 11Q3 11Q4 12Q1 12Q2  12Q3    12Q4   13Q1  13Q2    13Q3   13Q4    14Q1   14Q2
 0   0   0   0   0   0   0   0   0    0    0    0    0    0    0    0    0    0   6104.8  7315.6  0    12710.7 7263.1 15241.3 9634.4 29373.9

Upvotes: 1

Views: 48

Answers (2)

Ruthger Righart
Ruthger Righart

Reputation: 4921

I think the following does it. First it selects the elements in Cr that are found in Mdates:

A<-Cr[ ,1]
B<-which(A %in% Mdates)
Crnew<-Cr[B, ]

The following step provides the summed values for each category:

fac <- as.factor(Crnew[ ,1])
num <- as.numeric(Crnew[ ,2])
x <-data.frame(fac, num)
tapply(x$num, x$fac, FUN=sum)

Upvotes: 2

akrun
akrun

Reputation: 887501

You could try:

 res <- tapply(as.numeric(Cr[,2]), factor(Cr[,1], levels=unique(Mdates)), FUN=sum)
 res[is.na(res)] <- 0

  res
  # 8Q1   8Q2   8Q3   8Q4   9Q1   9Q2   9Q3   9Q4  10Q1  10Q2  10Q3  10Q4  11Q1 
  # 0     0     0     0     0     0     0     0     0     0     0     0     0 
  #11Q2  11Q3  11Q4  12Q1  12Q2  12Q3  12Q4  13Q1  13Q2  13Q3  14Q1  14Q2 
  #  0     0     0     0     0  6105  7316     0 12711  7263  9634 29374 

Upvotes: 2

Related Questions