[R] List of "occurrence" matrices
Dan Davison
davison at stats.ox.ac.uk
Thu Aug 7 16:03:53 CEST 2008
Lauri Nikkinen wrote:
>
> R users,
>
> I don't know if I can make myself clear but I'll give it a try. I have
> a data.frame like this
>
> x <- "var1,var2,var3,var4
> a,b,b,a
> b,b,c,b
> c,a,a,a
> a,b,c,c
> b,a,c,a
> c,c,b,b
> a,c,a,b
> b,c,a,c
> c,a,b,c"
> DF <- read.table(textConnection(x), header=T, sep=",")
> DF
>
> and I would like to sum all the combinations/occurences by a factor
> (letter in this case) between variables and produce a list of
> "occurrence" matrices. For example in this case the "occurrence"
> matrix (first element of list) for factor "a" should look like this
>
>>occulist
> $a
> var1 var2 var3 var4
> var1 x 0 1 1
> var2 0 x 1 2
> var3 1 1 x 1
> var4 1 2 1 x
>
> $b
> etc.
>
> because there is two rows where var2 and var4 has "a"
>
>
> I think this does it:
>
> occur.matrices <- function(df) {
> levels <- levels(unlist(df))
> ans <- lapply(levels, function(level) crossprod(df == level))
> structure(ans, names=levels)
> }
>
> Dan
>
>> occur.matrices(DF)
> $a
> var1 var2 var3 var4
> var1 3 0 1 1
> var2 0 3 1 2
> var3 1 1 3 1
> var4 1 2 1 3
>
> $b
> var1 var2 var3 var4
> var1 3 1 0 1
> var2 1 3 1 1
> var3 0 1 3 1
> var4 1 1 1 3
>
> $c
> var1 var2 var3 var4
> var1 3 1 0 1
> var2 1 3 0 1
> var3 0 0 3 1
> var4 1 1 1 3
>
>
>
> DF[DF$var2=="a" & DF$var4=="a",]
>
> Can you give an advice how to achieve this kind of a list of matrices?
>
> -Lauri
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
--
View this message in context: http://www.nabble.com/List-of-%22occurrence%22-matrices-tp18870809p18871268.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list