Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion of changing the "don't grow your results" example #782

Open
marioa opened this issue May 18, 2022 · 0 comments
Open

Suggestion of changing the "don't grow your results" example #782

marioa opened this issue May 18, 2022 · 0 comments

Comments

@marioa
Copy link

marioa commented May 18, 2022

In:

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
  }
} 
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant