r-novice-gapminder
r-novice-gapminder copied to clipboard
Suggestion of changing the "don't grow your results" example
In:
- https://swcarpentry.github.io/r-novice-gapminder/07-control-flow/index.html
You have:
output_vector <- c()
for (i in 1:5) {
for (j in c('a', 'b', 'c', 'd', 'e')) {
temp_output <- paste(i, j)
output_vector <- c(output_vector, temp_output)
}
}
output_vector
But then the improved example you provide is different:
output_matrix <- matrix(nrow = 5, ncol = 5)
j_vector <- c('a', 'b', 'c', 'd', 'e')
for (i in 1:5) {
for (j in 1:5) {
temp_j_value <- j_vector[j]
temp_output <- paste(i, temp_j_value)
output_matrix[i, j] <- temp_output
}
}
output_vector2 <- as.vector(output_matrix)
output_vector2
I think it would be much better if it was closer to the original example, e.g.
output_vector <- vector(length=25)
k <- 1
for (i in 1:5) {
for (j in c('a', 'b', 'c', 'd', 'e')) {
output_vector[k] <- paste(i, j)
k <- k+1
}
}
To reduce the cognitive load of beginners. You could even show that the better example is quicker, e.g.
system.time({
output_vector <- c()
for (i in 1:500) {
for (j in c('a', 'b', 'c', 'd', 'e')) {
temp_output <- paste(i, j)
output_vector <- c(output_vector, temp_output) # avoid
}
}
})
system.time({
output_vector <- vector(length=2500)
k <- 1
for (i in 1:500) {
for (j in c('a', 'b', 'c', 'd', 'e')) {
output_vector[k] <- paste(i, j)
k <- k+1
}
}
})