1. सीखें
  2. /
  3. पाठ्यक्रम
  4. /
  5. Writing Efficient R Code

Connected

अभ्यास

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.

निर्देश

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