[R] formating for dist function

Gabor Grothendieck ggrothendieck at gmail.com
Sat Aug 5 15:08:33 CEST 2006


Here are three ways:

# read in data
Lines <- "object1 object1 78
object1 object2 45
object1 object3 34
object1 object4 45
object2 object2 89
object2 object3 32
object2 object4 13
"
DF <- read.table(textConnection(Lines))

# 1 - xtabs
xt <- as.matrix(xtabs(V3 ~., DF))

# 2 - reshape
wide <- reshape(DF, direction = "wide", idvar = "V1", timevar = "V2")
rownames(wide) <- wide$V1
colnames(wide) <- sub(".*[.]", "", colnames(wide))
wide <- as.matrix(wide[,-1])

# 3 - [
mat <- matrix(0, nlevels(DF$V1), nlevels(DF$V2),
	dimnames = list(levels(DF$V1), levels(DF$V2)))
mat[cbind(DF$V1, DF$V2)] <- DF$V3


On 8/5/06, Ffenics <ffenics2002 at yahoo.co.uk> wrote:
> Hi there
> I have a list that looks like this
> object1 object1 78
> object1 object2 45
> object1 object3 34
> object1 object4 45
> object2 object2 89
> object2 object3 32
> object2 object4 13
>
> but i want to create a matrix like this in order to use the dist function of R
>
>
>             object1       object2         object3          object4
> object1   78          45          34            45
>
> object2        45                     89                     32                        13
>
> Is there a method in R that will take a list and format it in this way?
>
> Any help much appreciated.
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>



More information about the R-help mailing list