Skip to content

managing for-loops

1 message · Stephan Holl

#
Dear R-List, 
I succesfully managed to implement a SELECT query in a loop, so that the
results are stored in different data.frames.
Now I want to apply another function via for-loop, but nothing happens.
the new function calculates the mode of a distribution and returns a
vector.
I would like to store the vector in seperate objects in a for-loop, but
it fails. 

get.modal <- function(x) {
 x.elem<-sort(unique(x))
 x.count<-sapply(x.elem,esum<-function(elem,vec)
return(sum(vec==elem)),x)
 max.count<-max(x.count)
 modalwert <- x.elem[x.count == max.count]
 return(modalwert)
}

# collect vector with object-names to use in the loop
names <- ls(pat="EZG");names
[1] "EZG.ezg34.crossid.15" "EZG.ezg34.crossid.16" "EZG.ezg34.crossid.17"
[4] "EZG.ezg34.crossid.22" "EZG.ezg34.crossid.34" "EZG.ezg34.crossid.48"
[7] "EZG.ezg34.crossid.78"

# loop through all files and calculate mode:
for (i in names)
{
 new.names  <- paste(i, "index", sep=".")
  assign(new.names, get.modal(i$s))
 }

$s is the specific column on which the mode shuold be calculated.

Thank you for your help

Stephan Holl