[R] convert dataframe to matrix for cmdscale

William Simpson william.a.simpson at gmail.com
Wed Dec 10 20:04:34 CET 2008


Thanks Henrique

Here's what I came up with

temp<-read.table(filename, header=TRUE)
tempm<-tapply(temp[,3],temp[,1:2],c) #put dataframe into matrix form
tempm<-(tempm + t(tempm))/2 #add matrix to matrix flipped about
diagonal and divide by 2

Bill

On Wed, Dec 10, 2008 at 1:29 PM, Henrique Dallazuanna <wwwhsd at gmail.com> wrote:
> Try this:
>
> x$zMean <- ave(x$z,
>                            apply(x[,1:2], 1, function(x)paste(sort(x),
> collapse = "")),
>                            FUN = mean)
>
> xtabs(zMean ~ x + y, data = x)
>
>
> On Wed, Dec 10, 2008 at 11:16 AM, William Simpson
> <william.a.simpson at gmail.com> wrote:
>>
>> On re-reading ?cmdscale I see that I can also use cmdscale(d) on a
>> full matrix rather than just the lower triangle.
>>  d: a distance structure such as that returned by 'dist' or a
>>          full symmetric matrix containing the dissimilarities.
>>
>> So how to get a full symmetric matrix from a dataframe like this (toy
>> example)?
>>  x       y       z
>>  "a"     "a"     0
>>  "a"     "b"     1
>>  "a"     "c"     2
>>  "b"     "a"     .9
>>  "b"     "b"     0
>>  "b"     "c"     1.3
>>  "c"     "a"     2.2
>>  "c"     "b"     1.1
>>  "c"     "c"     0
>>
>> Replacing the corresponding cells in the matrix by their means, I need
>> this:
>>
>>  c 2.10 1.20 0.00
>>  b 0.95 0.00 1.20
>>  a 0.00 0.95 2.10
>>  a    b    c
>>
>> E.g. in the original data, the cell (a,b) = 1; (b, a) =0.9. In the
>> final matrix, (a,b) = (b,a) =0.95
>>
>>  Thanks very much for any help.
>>
>> Bill
>>
>> ______________________________________________
>> 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.
>
>
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>



More information about the R-help mailing list