neticin
neticin

Reputation: 159

Implementing a R code in C

I use R and I implemented a Monte Carlo simulation in R which takes long time because of the for loops. Then I realized that I can do the for loops in C, using R API. So I generate my vectors, matrices in R then I call functions from C(which will do the for loops) and finally I present my results in R. However, I only know the basics of C and I cannot figure how to transform some functions to C. For instance I start with a function in R like this:

t=sample(1:(P*Q), size=1)

How can I do this in C? Also I have an expression in R:

A.q=phi[,which(q==1)] 

How can I use "which" expression in C?

Upvotes: 1

Views: 166

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121177

Before you start writing C code, you would be better off rewriting your R code to make it run faster. sample is vectorised. Can you move the call to it outside the loop? That should speed things up. Even better, can you get rid of the loop entirely?

Also, you don't need to use which when you are indexing. R accepts logical vectors as indicies. Compare:

A.q=phi[,which(q==1)]
A.q=phi[,q==1]

Finally, I recommend not calling your variables t or q since there are functions with those names. Try giving your variables descriptive names instead - it will make your code more readable.

Upvotes: 3

Related Questions