Yet another way to use R in Excel for .NET programmer

[This article was first published on My Life as a Mock Quant in English, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I wrote the article whose title is “Another way to use R in Excel for .NET programmer” last night.
In that article, We need to use IDE to write C# program.

On ther other hand, Excel-DNA give us easier way to create XLL.
Let me show you one example.

In last post, I downloaded two libraries.

  1. Excel-DNA
  2. R.NET

If you don’t download these files yet, please do it.
And, put the files which I showed below together into some folder.
I changed the file name of ExcelDna.xll and ExcelDna.dna to SimpleExample.xll and SimpleExample.dna.
It is no problem for you to change these names as you like.

Next, Please copy and paste below codes to SimpleExample.dna by notepad or such a editor and save & close dna file.

<DnaLibrary RuntimeVersion="v4.0" Name="My First XLL" Language="CS">
<ExternalLibrary Path="R.NET.dll" />
<Reference Name="R.NET" />

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna.Integration;
using RDotNet;

namespace CSLib
    public class CSLib
        static REngine rengine = null;
        static CSLib()
            // Set the folder in which R.dll locates.
            REngine.SetDllDirectory(@"C:\Program Files\R\R-2.13.0\bin\i386");
            rengine = REngine.CreateInstance("RDotNet", new[] { "-q" });
        [ExcelFunction(Description = "get random numbers obey to normal distribution")]
        public static double [] MyRnorm(int number)
            return (rengine.EagerEvaluate("rnorm(" + number + ")").AsNumeric().ToArray<double>());


If you use or install another version R, modify “SetDllDirectory” function call.

Lanch SimpleExample.xll and create new Excel sheet. As you’ll see below, you can use your own function defined in C# language !

Enjoy !

*R.NET seems to be compiled with .NET framework 4.0. you may have to install these to try this example.

To leave a comment for the author, please follow the link and comment on their blog: My Life as a Mock Quant in English. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)