4. wrong: right:
my.plot <- function(name) {
plot(density(M[ , name]),
main=name)
rug(M[ , name])
}
# M is defined outside my.plot
my.plot("msn2_del")
my.plot("ssn6_del")
my.plot("ctr9_del")
# Avoid global variables; pass them in as arguments
my.plot <- function(mat, name) {
x <- mat[,name]
plot(density(x), main=name)
rug(x)
}
my.plot(M, "msn2_del")
my.plot(M, "ssn6_del")
my.plot(M, "ctr9_del")
5. Even less copy-pasting: for-loops
for ( some.variable in some.vector) {
cat( some.variable, “n”)
}
The statements inside the curly braces are executed as many times
as the length of some.vector, with some.variable getting each of the
values in some.vector in turn.
deletions <- c(“msn2_del”, “ssn6_del”, “ctr9_del”)
for (del in deletions) {
my.plot(M, del)
}
6. Iteration using for-loops
for (cutoff in c(0.001, 0.01, 0.05)) { # start of block
print.performance(data, p=cutoff) # note indentation
} # end of block
for (TF in colnames(data) ) {
txpts <- select.txpts(data, TF, k=3, limit=0.5)
network <- network.add(network, data, TF, txpts)
}
7. Avoid loops if you can use aggregates or apply()
# don’t:
total <- 0
for(i in 1:length(x)) {
total <- total + (x[i])^2
}
# … or:
means <- rep(NA, ncol(data))
for (col in 1:ncol(data)) {
means[col] <- mean(data[,col])
}
# do:
sum(x^2)
apply(data, 2, mean)