LoslegenKostenlos loslegen

Vectorized code: multiplication

The following piece of code is written like traditional C or Fortran code. Instead of using the vectorized version of multiplication, it uses a for loop.

x <- rnorm(10)
x2 <- numeric(length(x))
for(i in 1:10)
    x2[i] <- x[i] * x[i]

Your job is to make this code more "R-like" by vectorizing it. x is available for you to use.

Diese Übung ist Teil des Kurses

Writing Efficient R Code

Kurs anzeigen

Anleitung zur Übung

  • Read the example code above, and try to understand what it is calculating.
  • Rewrite that code using a vectorized solution. Hints:
    • Your solution should be a single line of code.
    • You should not use a for loop.
    • The multiplication operator is vectorized!

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

# Store your answer as x2_imp
x2_imp <-
Code bearbeiten und ausführen