rt.l
rt.l

Reputation: 306

Create matrix after aggregate a table in R

I am really new at R (i've been learning it for 1 week now) and even newer at Stack Overflow. I have a doubt about how to use the aggregate function. I am trying the following code:

a = aggregate(dom$pesoA, 
               by = list(tipoE = addNA(dom$typeEsg), mun =dom$codMun), 
               FUN = sum, 
               na.rm=FALSE)

where: - dom$pesoA has only the values that I need to sum - dom$typeEsg has numbers from 1 to 6 and also many NAs - dom$codMun has municipalities codes (no NAs)

Can I transform this data frame (a) into a matrix where tipoE are the columns, mun are the rows and the sum value of dom$pesoA are the elements of my matrix (there are some missing combination of mun and tipoE)?

I dont know if you can understand my explanation, if you have any questions I will try to answer it.

This is what my a df looks like

Thanks in advance

TR

Upvotes: 1

Views: 1127

Answers (1)

IRTFM
IRTFM

Reputation: 263411

If your dataframe really does look like that then there is a serious mismatch between your column names and your code.

dom <- data.frame(tipoE=sample(c(letters[1:4],NA), 30, rep=TRUE),
mun=rep(c(3200102,3200106,3200310) , each=10),
x=runif(30, 100,200) )
dom

This reworking succeeds:

a = aggregate(dom$x, 
               by = list(tipoE = addNA(dom$tipoE), mun =dom$
               FUN = sum)
a

This use of xtabs then gives your requests:

> aT <- xtabs( x ~ tipoE + mun, a)
> aT
      mun
tipoE   3200102  3200106  3200310
  a    340.7700 367.1412 180.0594
  b    280.9851 485.8780 798.4880
  c    280.7682 236.3637 165.2295
  d    176.6967 125.0732 132.5339
  <NA> 376.4278 117.1063 251.2514

Upvotes: 2

Related Questions