Re: [R] factor manipulation: edgelist to a matrix?

From: Dimitris Rizopoulos <dimitris.rizopoulos_at_med.kuleuven.be>
Date: Thu, 20 Dec 2007 09:25:50 +0100

one way is the following:

V1 <- c(1,1,1,2,3,3,3,3)
V2 <- LETTERS[c(1,1,2,1,3,1,3,2)]

tab <- table(V1, ave(V1, V1, FUN = seq_along)) vals <- as.vector(t(tab))
vals[vals != 0] <- unlist(split(V2, V1)) vals[vals == 0] <- NA
matrix(vals, nrow(tab), ncol(tab), TRUE)

I hope it helps.

Best,
Dimitris



Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium

Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://med.kuleuven.be/biostat/
     http://www.student.kuleuven.be/~m0390867/dimitris.htm


> Hello All,
>
> I have had considerable bad luck with attempting the following with
> for
> loops. Here is the problem:
>
>
> # Suppose we have a data.frame with the following data, which can be
> considered a type of edgelist (for those with networks backgrounds):
> #
> # V1 V2
> # 1 A
> # 1 A
> # 1 B
> # 2 A
> # 3 C
> # 3 A
> # 3 C
> # 3 B
> #
> # I want the output of the function to produce a matrix, such that
> #each
> factor of V1 is a row, and each corresponding value at position k of
> V2 is
> the i,j^th element of the new matrix, with missing values otherwise.
> The
> desired output should be:
> # [,1] [,2] [,3] [,4]
> # [1,] A A B NA
> # [2,] A NA NA NA
> # [3,] C A C B
>
> I have explored the reshape package as well as the network package
> in this
> pursuit, with no luck.
>
> Thanks,
> Chris Marcum
> UCI Sociology
>
> ______________________________________________
> 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.
>

Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm



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. Received on Thu 20 Dec 2007 - 09:38:44 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 20 Dec 2007 - 10:30:19 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.