LoslegenKostenlos starten

Vectorized code: calculating a log-sum

A common operation in statistics is to calculate the sum of log probabilities. The following code calculates the log-sum (the sum of the logs).

# x is a vector of probabilities
total <- 0
for(i in seq_along(x)) 
    total <- total + log(x[i])

However this piece of code could be significantly improved using vectorized code.

Diese Übung ist Teil des Kurses

<Kurs>Writing Efficient R Code</Kurs>
Kurs ansehen

Übungsanweisungen

  • Find the log-sum of x using the log() and sum() functions, simplify the above loop.
  • Store your answer in the object log_sum.

Interaktive praktische Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# Initial code
n <- 100
total <- 0
x <- runif(n)
for(i in 1:n) 
    total <- total + log(x[i])

# Rewrite in a single line. Store the result in log_sum
log_sum <- ___
Code bearbeiten und ausführen