[R] Matrix Another table

Sarah Goslee sarah.goslee at gmail.com
Tue Mar 13 16:33:12 CET 2012


Hi,

On Tue, Mar 13, 2012 at 7:51 AM, RMSOPS <ricardosousa2000 at clix.pt> wrote:
> I have next table
> source destine
> 3 3
> 7 7
> 6 6
> 3 4
>  4 4
>  4 3
> 3 3
> 3 3
>  3 3
>  3 3
> 3 4
>  4 4
>  4 3
>  3 4
>  4 3

It is so much easier if you use dput to provide reproducible data, as
the posting guide asks. There's no way for us to tell, for instance,
that you expect those to be factors with levels 1:7.

Here's how:

> dput(testdata)
structure(list(source = structure(c(3L, 7L, 6L, 3L, 4L, 4L, 3L,
3L, 3L, 3L, 3L, 4L, 4L, 3L, 4L), .Label = c("1", "2", "3", "4",
"5", "6", "7"), class = "factor"), destine = structure(c(3L,
7L, 6L, 4L, 4L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 3L, 4L, 3L), .Label = c("1",
"2", "3", "4", "5", "6", "7"), class = "factor")), .Names = c("source",
"destine"), row.names = c(NA, -15L), class = "data.frame")

Also, df is a base function, and thus a bad thing to name your data frame.

>  I'm trying to create an array with the number of occurrences between the
> source and destination. id_ap<-levels(factor(df$v_source))
> num_AP<-length(levels(factor(df$v_source)))
> mat<-matrix(data=NA,nrow=num_AP,ncol=num_AP,
> byrow=TRUE,dimnames=list(id_ap,id_ap))
> 1 2 3 4 5 6 7
> 1 NA NA NA NA NA NA NA
> 2 NA NA NA NA NA NA NA
> 3 NA NA NA 4 NA NA NA 4
> NA NA NA NA NA NA NA 5
> NA NA NA NA NA NA NA 6
> NA NA NA NA NA NA NA 7
> NA NA NA NA NA NA NA

Why not just use table?

> table(testdata$source, testdata$destine)

    1 2 3 4 5 6 7
  1 0 0 0 0 0 0 0
  2 0 0 0 0 0 0 0
  3 0 0 5 3 0 0 0
  4 0 0 3 2 0 0 0
  5 0 0 0 0 0 0 0
  6 0 0 0 0 0 1 0
  7 0 0 0 0 0 0 1


> what better way to count the occurrences of the table, for example 3-4 = 4
> times

That I can't tell you, since there are only three occurences of 3-4 in
your data. If you want that value to be equal to 4, you'll need to
provide more information about your problem.

Sarah


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



More information about the R-help mailing list