[R] How to append to a list dynamically?
David Winsemius
dwinsemius at comcast.net
Wed Jun 17 16:40:30 CEST 2009
On Jun 17, 2009, at 7:52 AM, Nick Angelou wrote:
> I have a problem with dynamic appending to a list. Here is the list
> variable:
>
>
> clusters <- vector("list", 0)
>
library(fortunes)
fortune("dog")
I would suggest that referring to a character vector as a "list", and
then also calling an element in that vector "list" is akin to calling
your cat, "dog", and then calling its tail, "dog", as well.
>
> I extended in the function below:
>
>
> cluster <- function (pair, clusters)
> {
> found <- FALSE
> for (i in length(clusters))
> {
> if (length(intersect(pair, clusters[i])) > 0)
> {
> clusters[i] <- union(clusters[i], pair)
> found <- TRUE
> }
> }
> if (!found)
> {
> clusters <- list(clusters, as.vector(pair))
So the first time cluster() is called, it would need to handle a
vector correctly, but now you have changed clusters to be a list and
the second call to clusters will need to handle a list correctly.
> }
> }
>
>
> The function is executed in a loop:
>
>
> for (i in 1:nrow(adjMatrix))
> {
> for (j in 1:nrow(adjMatrix))
> {
> if ((i != j) && adjMatrix[i,j] >0) # the matrix element has to be
> non-zero
> in order to be clustered
> {
> cat(rownames(adjMatrix)[i], colnames(adjMatrix)[j], "\n")
> cluster(as.vector(c(rownames(adjMatrix)[i], colnames(adjMatrix)
> [j])),
> clusters)
> }
> }
> }
>
>
> But the list variable remains empty (i.e. length(clusters) = 0) even
> though
> it should not. Somehow the dynamic extension of the list does not
> work in
> this case. Any suggestions?
Use appropriate naming and do not conflate "vector" with "list". They
need different functions to properly access elements or extend their
lengths.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list