[R-sig-eco] change list into interaction matrix

Sarah Goslee sarah.goslee at gmail.com
Mon Mar 26 21:59:59 CEST 2012


Would this work for you:

> with(dados, ifelse(table(parasito, hospedeiro) > 0, 1, 0))
        hospedeiro
parasito 1 2 3
       a 1 0 0
       b 1 0 0
       c 0 1 0
       d 0 1 1


On Mon, Mar 26, 2012 at 3:55 PM, Augusto Ribas <ribas.aca at gmail.com> wrote:
> Hello dear list.
> I have a problem that could use some help.
> I have a list of parasites and its hosts and want to change it to a
> interaction matrix.
> I try some functions on the package bipartite put couldn't solve my problem.
> If someone could lend a hand i made an example:
>
> #data type example
> dados<-data.frame(parasito=c("a","b","b","c","d","d"),
>                  hospedeiro=c("1","1","1","2","2","3"))
> #how i see them
> dados
>
> #i need a matrix like this
> matriz<-matrix(data=NA,nrow=length(unique(dados$parasito)),
>               ncol=length(unique(dados$hospedeiro)),
>               dimnames=list(c(as.character(unique(dados$parasito))),
>               c(as.character(unique(dados$hospedeiro)))))
>
> #now i need to fill the matrix with 1 and 0 in presence and absent of
> interactions
> matriz
>
> #I imagined something like this
> #line 1 of the list versus matrix colum 1 and line 1
> matriz[1,1]<-ifelse(colnames(matriz)[1]==dados$hospedeiro[1]
>       & rownames(matriz)[1]==dados$parasito[1]
>       ,1,0)
>
> matriz
>
> #line 1 of the list versus matrix colum 2 and line 1
> matriz[1,2]<-ifelse(colnames(matriz)[2]==dados$hospedeiro[1]
>       & rownames(matriz)[1]==dados$parasito[1]
>       ,1,0)
>
> matriz
>
> #----------------------------------------
>
> My problem is that with something like this i need to test each matrix
> object with all the list. very inefficient.
> Can someone see a more efficient an easy solution to do this?
>
> OBS: The example is in portugues, parasito = parasite and hospedeiro = host
> :)
>
> --
> Grato
> Augusto C. A. Ribas
>

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



More information about the R-sig-ecology mailing list