# Tag Info

18

I started with the Julia code you had and also got ~20 seconds, so I think my timings are similar to yours. Let me give a step by step breakdown on how to do this. To start, notice that if you are running code in the REPL that variables defined there are global. This incurs a good performance cost. There are two ways to deal with this: 1) Wrap it all in a ...

16

Here is how I would rewrite your code, comments to follow. simulated_annealing <- function(func, s0, niter = 10, step = 0.1) { # Initialize ## s stands for state ## f stands for function value ## b stands for best ## c stands for current ## n stands for neighbor s_b <- s_c <- s_n <- s0 f_b <- f_c <- f_n <- func(...

15

Here is how I would rewrite your code. I will add my comments after: plotActivity <- function( activity = 'codereview.stackexchange.com', api_key = getOption('rescuetime_api_key'), from_date = NULL, to_date = NULL) { ## This function plots time spent on a given URL ## using the rescue time API ## ## Arguments: ## - activity: the url ...

13

Your approach is an example of good R code. However, there is a base function that allows creating a cartesian product of strings, interaction. This function creates a factor, and the levels are equivalent to the cartesian product. Furthermore, instead of paste(..., sep = "") you can use paste0(...). If you use these functions, your code will be much ...

11

You can use the function vapply. The help page of ?vapply says: vapply is similar to sapply, but has a pre-specified type of return value, so it can be safer (and sometimes faster) to use. You can use vapply(xz, function(col) col + 100, FUN.VALUE = numeric(nrow(xz)) The argument FUN.VALUE is used to tell the vapply what the function returns. Since ...

11

Nice initiative! And R is perfect for this kind of stuff. Conditional logic if(!require("lattice")){ install.packages("lattice") } require("lattice") If the first require was successful, then no need to call it again. You can move the second inside the if: if(!require("lattice")){ install.packages("lattice") require("lattice") } Coding style For ...

10

As you realize, your first approach works (it gives a result consistent with the criteria you specify), but it is not idiomatic R. Iterating over elements of a set/list/vector is idiomatic of python, and does have a place in R as well. However, what this approach misses is 2 aspects of R: inherent vectorization and the factor data type. In R, all basic ...

10

Just to add to @flodel's comments, here is a properly vectorized version. One can see this is quite a bit faster, outperforming the parallel option (on 7 cores) by a factor 5. This problem is a quite nice demonstration of why is is worth your time to think about vectorized code: flodel_fizzbuzz <- function(range = 100, fizz = 3, buzz = 5) { s <- 1:...

9

The fundamental ideas of your code are solid, however there are a couple of areas that could be improved. For starters, when you call sample and you only want one number returned, you can make use of the size argument. For vectors of only size 3, as in your case, there isn't much difference: library(microbenchmark) microbenchmark(sample(doors, size = 1), ...

7

R has vectorized operators and using those is much more efficient in this case: Monty_Hall2 <- function(repetitions){ doors <- c('A','B','C') winning_door <- sample(doors, repetitions, replace=TRUE) contestant_choose <- sample(doors, repetitions, replace=TRUE) stay_wins <- winning_door == contestant_choose switch_wins <-...

7

Here is a proposal for a different approach that doesn't use a for loop and has some simplifications. First, an example data frame: dat <- data.frame(a1 = 9:11, a2 = 2:4, a3 = 3:5, b1 = 4:6, b2 = 5:7, b3 = 1:3) # a1 a2 a3 b1 b2 b3 # 1 1 2 3 4 5 6 # 2 2 3 4 5 6 7 # 3 3 4 5 6 7 8 Now, we set the number of columns per ...

7

Here are my main recommendations: use recursion use names instead of list indices, for example node$data$reply$data$children reads much better than node[[2]][[5]][[2]][[2]] and it is also more robust to data changes. use well-named variables so you code reads easily Now for the code: url <- "http://www.reddit.com/r/funny/comments/2eerfs/...

7

For each group in your data table, your code computes the coefficient b1 from a linear regression y = b0 + b1*x + epsilon, and you want to run this regression and obtain b1 for observations 1-12, 2-13, 3-14, ..., 989-1000. Right now you are separately calling lm for each data subset, which is a non-vectorized approach. Vectorization of prediction models ...

6

This is a general do-it-yourself answer to "my code is slow, what can I do?": Use the profiler. Rprof(tmp <- tempfile()) ############################# #### YOUR CODE GOES HERE #### ############################# Rprof() summaryRprof(tmp) unlink(tmp) Yes, there is a bit of a learning curve about interpreting the output, but you could try to find the ...

6

Revised: ...I wonder if this could replace those two loops? Here are the results with the test vector offered in your comments: set.seed(100); m=rnorm(15); std_d <- sd(m) Reduce(function(y,xx){ if( abs(tail(y[!is.na(y)], 1) - xx) > std_d ) {c(y,NA)}else{ c(y,xx)} }, m ...

6

I spent clearly too much time on this... Main ideas: your understanding of how the payment on a fixed mortgage is computed was wrong. The payment is computed once at the beginning and remains the same regardless of prepayments, which is why people who choose to prepay end up repaying their whole mortgage before the scheduled term, as the example below ...

6

The following function works without for loops or any function of the *apply family. Furthermore, it does not require additional packages but makes use of base functions only. See the code comments for further details. significant_drydowns <- function(rain, threshold = 10, k = 48) { # all values except the first one rain_tail <- rain[-1L] # ...

6

Looping is generally not recommended in R. And it's not really needed here. As @vnp pointed out in a comment, all you need is simply calculate the least common multiple of the values in the input vector, let's call it lcm, and apply the formula lcm * (max // lcm) (with integer division). The pracma library already has an implementation of the least common ...

6

in your MATLAB code, some unnecessary steps can be skipped. Here's a modification of your doStep function that should improve performance quite a bit. Each modif is explained in the comments within the code. doStep2.m function file: function [ newtv ] = doStep2( tv, fitnessf, mutrate, stdev ) % Function to calculate new offspring trait values from parent ...

6

Assuming your data are numeric and your columns are ordered by D-#, the following approaches should work: Using apply: errorarray$Q1 <- apply(errorarray[, c(3, 6, 7, 14:16)], 1, sum) # using col indices errorarray$Q1 <- apply(errorarray[c("D-03", "D-06", "D-07", "D-15", "D-16")], 1, sum) # using column names Using rowSums: errorarray\$Q1 <- ...

6

Overall your code is not bad, but we can do better. Let's start with the coding style. Your variables are clearly named and your code is easy to follow, however the use of & is not necessary. const NumericVector &x R objects are always passed by reference in Rcpp even without the &. Dirk has some slides (see 29,30) with more information about ...

5

Here's a faster way: add_2maxFaster <- function(x) { imax1 <- which.max(x) imax2 <- which.max(x[-imax1]) if (imax2 >= imax1) imax2 <- imax2 + 1L c(x, x[imax1], x[imax2], imax1, imax2) } set.seed(42) m <- matrix(runif(1e6), 1e4) # Compare speed: system.time( a1<-apply(m, 1, add_2max) ) # 0.38 secs system.time( a2<-...

5

I didn't read in it's entirity, but change this line static int mannwhit(std::vector<int> c, std::vector<int> sizes) to static int mannwhit(const std::vector<int>& c, const std::vector<int>& sizes) This won't speed up your code but you should use #include <cstdio> //instead of stdio.h and ...

5

You can avoid appending to vectors (which can cause re-allocation of space and can considerably slow things down in principle; though in your case of only a length 10 vector that shouldn't be noticeable) if you allocate them to the needed size initially and then assign within them. result <- vector("numeric", 10) # or even: result <- numeric(10) n <...

5

I feel you wrote some very complicated code when the hardest part (from an algorithm point of view) should be a single merge of your two data.frames. So my rewrite is centered around a call to the base merge function. The only trick is to add an is column to both data.frames before merging so the output data.frame M will contain two is.new and is.old columns ...

5

The for loop can be replaced with a lapply statement. Using base R functions, your read_season_range example is equivalent to the following one-liner: sixties <- do.call(rbind, lapply(1960:1969, read_season)) or to wrap it in a function: read_season_range <- function(year_range) { do.call(rbind, lapply(year_range, read_season)) }

5

Parallelization is not necessarily implemented nicely in R. However, it is far more ideal to use R's batch process than opening 10x Rstudio sessions as you saw (less of a resource drain per task). Cores, cores, where art thou? The first thing I would do is find out how many cores you have access to. Within this script 4 seem to be allocated. It is very ...

5

This is one of many instances where people would be tempted to say, "see, loops in R are slow". And my response is, "loops aren't that slow, but you can put slow code in loops." There's no reason res needs to be a data.frame. Leave it as a matrix and your code runs in under a second on my laptop. # initialize res res <- matrix(rep(NA,totCombs*totChars)...

Only top voted, non community-wiki answers of a minimum length are eligible