Skip to content
Prev 257386 / 398506 Next

Odp: Data frame with 3 columns to matrix

Hi


Michael Bach <phaebz at gmail.com> napsal dne 19.04.2011 14:21:13:
this
element
and
have
They are there

try str(tab)

With little effort you can get exactly the structure you want.
x  y zdata
1 2  5     1
2 2  6     1
3 3  7     1
4 3  8     1
5 3  9     1
6 5 10     2
7 5 11     2
8 5 12     2
tab<-xtabs(zdata~x+y, data)
tab[tab==0]<-NA
tab
   y
x    5  6  7  8  9 10 11 12
  2  1  1 
  3        1  1  1 
  5                 2  2  2
str(as.matrix(tab))
 xtabs [1:3, 1:8] 1 NA NA 1 NA NA NA 1 NA NA ...
 - attr(*, "dimnames")=List of 2
  ..$ x: chr [1:3] "2" "3" "5"
  ..$ y: chr [1:8] "5" "6" "7" "8" ...
 - attr(*, "class")= chr [1:2] "xtabs" "table"
 - attr(*, "call")= language xtabs(formula = zdata ~ x + y, data = data)

tab1<-cbind(as.numeric(rownames(tab)), tab)
rbind(c(NA,as.numeric(colnames(tab))), tab1)
      5  6  7  8  9 10 11 12
  NA  5  6  7  8  9 10 11 12
2  2  1  1 NA NA NA NA NA NA
3  3 NA NA  1  1  1 NA NA NA
5  5 NA NA NA NA NA  2  2  2
rbind(c(NA,as.numeric(colnames(tab))), tab1)

If you want to get rid of column and row names set them to NULL.

Regards
Petr