Instruction: Define vectorization and provide an example of how it can optimize data operations in R.
Context: This question assesses the candidate's understanding of one of R's core principles for efficient computation.
Official answer available
Preview the opening of the answer, then unlock the full walkthrough.
To give you an example that highlights the efficiency of vectorization, let's consider a scenario where we need to calculate the square of every number in a large dataset. In a non-vectorized approach, one might loop through each element of the dataset and apply the squaring operation, which is not only verbose but also computationally expensive.
```R Non-vectorized approach numbers <- 1:1000000 # A large vector of numbers squared_numbers <- numeric(length(numbers)) # Initialize an empty vector to store results for (i in seq_along(numbers)) { squared_numbers[i] <- numbers[i]^2 } ```...