Iterate over lists stored in data.frame in R

I think this is a newbie, but I don’t have the right dictionary for an effective Google search.

I have data.frame, finalwhich contains a list clusters, each of which is a list of strings.

I would like to iterate over the list of rows in each cluster: the for loop in the for loop.

for (j in final$clusters){
    for (i in final$clusters$`j`){
        print final$clusters$`j`[i]
    }
}

jmatches lists in clusters, and imatches items inclusters[j]

I tried to do this using the length of each cluster, which I thought would be something like length(final$clusters[1]), but this gives 1, not the length of the list.

It also final$clusters[1]gives $ '1', and the next line contains all the rows in cluster 1.

Thank.

EDIT: output dput(str(final))as requested:

List of 2
 $ clusters     :List of 1629
  ..$ 1   :
  ..$ 2   : 
  ..$ 3   : 
  ..$ 4   : 
  ..$ 5   : 
  ..$ 6   : 
  ..$ 7   : 
  ..$ 8   : 
  ..$ 9   : 
  ..$ 10  : 
  .. [list output truncated]
 $ cluster_stats: num [1:1629, 1:6] 0.7 0.7 0.7 0.7 0.7 0.7 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:1629] "1" "2" "3" "4" ...
  .. ..$ : chr [1:6] "min" "qu1" "median" "mean" ...
NULL
+5
2

, list data.frame. , - .

, rapply. lapply.

:

## I create some reproducible example

clusters <- list(cluster1,cluster2)
cluster1 <- list(a='a',b='b')
cluster2 <- list(c='aaa',d='bbb')
final <- list(clusters)

, rapply

rapply(final,f=print)
[1] "a"
[1] "b"
[1] "aaa"
[1] "bbb"
    a     b     c     d 
  "a"   "b" "aaa" "bbb" 

OP

lapply, . [[ ( [, heder ), write.table. . (1.txt,...)

    lapply(names(final$clusters),
                      function(x)
                             write.table(x=final$clusters[[x]],
                                         file=paste(x,'.txt',sep='')))
+4

, , , , .

, - :

for (j in final$clusters){
    for (i in final$clusters[j]){
        print i
    }
}

: http://manuals.bioinformatics.ucr.edu/home/programming-in-r#TOC-For-Loop : http://www.statmethods.net/management/subset.html

+4

All Articles