Skip to content
Back to formatted view

Raw Message

Message-ID: <4766B219.7080206@biostat.ku.dk>
Date: 2007-12-17T17:30:01Z
From: Peter Dalgaard
Subject: convert table
In-Reply-To: <OFA64168E3.F38DB752-ON802573B4.005E69A4-802573B4.005E93AF@hsl.gov.uk>

Richard.Cotton at hsl.gov.uk wrote:
>> I have a table like this:
>>
>> coor   v1   v2   v3
>> x1   12   33   123 
>> x2   1   123
>> x3   12 
>> x4   33   1
>>
>> and I'd like to tranform this matrix in presence/absence data.frame
>>
>> coor   1   12   33   123
>> x1   0   1   1   1 
>> x2   1   0   0   1
>> x3   0   1   0   0 
>> x4   1   0   1   0
>>     
>
> #This uses the reshape package
> df = data.frame(coor = paste("x", 1:4, sep=""), v1=c(12,1,12,33), 
> v2=c(33,123,NA,1), v3=c(1,NA,NA,NA))
> mdf = melt(df)
> with(mdf, table(coor, value))
>   
Plain reshape() too:

> df = data.frame(coor = paste("x", 1:4, sep=""), v1=c(12,1,12,33),
+ v2=c(33,123,NA,1), v3=c(123,NA,NA,NA))
> mdf <- reshape(df, direction="long", varying=c("v1","v2","v3"), sep="")
> with(mdf, table(coor, v))
    v
coor 1 12 33 123
  x1 0  1  1   1
  x2 1  0  0   1
  x3 0  1  0   0
  x4 1  0  1   0

(actually, varying=-1 also works.)


-- 
   O__  ---- Peter Dalgaard             ?ster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907