[Traminer-users] repeating a command: loop and/or apply function

Matthias Studer Matthias.Studer at unige.ch
Tue Nov 12 15:03:32 CET 2013

Dear Jeremy,

If you want to build a variable name (such as diss4vs.hc) you need to use "get" and "paste0" functions. "paste0" is used to build the variable name (you can also use "paste", see help page). "get" is used to get the variable once the variable name has been built.

To access the variable diss4vs.hc you can use

get(paste0("diss", 4, "vs.hc"))

To write to a variable name use the "assign" function and "paste0",

In your case

assign(paste0("ward", 4, "vs"), thevalue)

Hence, your loop could look like

for (i in 1:7){

        clust <- hclust(as.dist(get(paste0("diss", i, "vs.hc"))), method = "ward", members = aggbhps.hc$aggWeights)

        assign(paste0("ward", 4, "vs"), clust)

I don't think that apply would be of any help hear. And the performance gain is only for long loop (here you only have 7 loops).

Hope this helps.

De : traminer-users-bounces at lists.r-forge.r-project.org [mailto:traminer-users-bounces at lists.r-forge.r-project.org] De la part de Jeremy Reynolds
Envoyé : mardi 12 novembre 2013 14:52
À : traminer-users at lists.r-forge.r-project.org
Objet : [Traminer-users] repeating a command: loop and/or apply function

Dear Traminer Users,

I am a novice R user, and I could use some advice about how to repeat commands in R.  I would like to run a clustering command repeatedly with 7 different dissimilarity matrices named diss1vs.hc through diss7vs.hc.  I tried the loop below, but it does not run properly.  I have also been reading about the various apply functions in R, but none of the examples I found so far seem to be doing what I need.  Can you please tell me 1) how I can make the loop below run and 2) what would be the equivalent (or perhaps better) solution using one of the apply functions?


for (i in 1:7){
  ward[i]vs <- hclust(as.dist(diss[i]vs.hc), method = "ward", members = aggbhps.hc$aggWeights)

> for (i in 1:7){

+   ward[i]vs <- hclust(as.dist(diss[i]vs.hc), method = "ward", members = aggbhps.hc$aggWeights)

Error: unexpected symbol in:

"for (i in 1:7){


> }

Error: unexpected '}' in "}"

Dr. Jeremy Reynolds
Associate Professor
Undergraduate Coordinator
Department of Sociology
116 Baldwin Hall
University of Georgia
Athens, GA 30602-1611
Phone: (706) 583-8072
Web: http://uga.edu/soc/people/faculty/reynolds_jeremy.php
Fax: (706) 542-4320
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/traminer-users/attachments/20131112/f29fbffd/attachment.html>

More information about the Traminer-users mailing list