- この記事の「なんちゃってRパッケージ」はこちら Here is the github containing files and directories handled in this note.
- Fortran関数を組み込んでみる Let's try fortran functions.
- 基本は同じで、use_rcpp()関数を使ってsrcフォルダを作り、そこにfortran関数を置く。そのfortranサブルーチンを呼び出すR関数を書き、ダイナミック・リンク・ライブラリの手当をする Almost similar to the case of C. make src directory with use_rcpp() and put your fortran functions in it. Write R function that uses the fortran subroutines and take care the dynamic link library issue.
- こちらにある、C,Fortranを組み込むtoy packageからfortranの簡単関数を拝借する Borrow and modify the simple and easy fortran file and R function here.
subroutine foo(x, n)
integer i
integer n
double precision x(n)
do 10 i = 1, n
x(i) = x(i) ** 2
10 continue
end
-
- Rの呼び出し関数 R function using the fortran subroutine.
@export
foo <- function(x) {
stopifnot(is.numeric(x))
out <- .Fortran("foo", x = as.double(x), n = length(x), PACKAGE = "ry4")
return(out$x)
}
- 手順は同じ Do the same as C.
- githubでレポジトリを作り Make a new github repository.
- そのクローンをデスクトップに作る Clone it on your local PC.
- 一方、devtoolsパッケージのcreate()関数を使ってパッケージの骨格を作り、さらにuse_rcpp()関数を使ってsrcフォルダを加える Make a skeleton of new package with create() function and add src directory with use_rcpp() function.
- それを一括してローカルのgitクローンにコピーして、そこにR関数、C関数、Fortran関数を置いて、document()する Copy-and-paste all to the github-clone directory and put R, C, and fortran files in R, src and src directories, respectively.
- それをgitでpushして git push them to github.
- install_github()する install_github from the github repository.
> library(ry4)
> foo(30)
[1] 900
> foo(1:10)
[1] 1 4 9 16 25 36 49 64 81 100
> foo
function (x)
{
stopifnot(is.numeric(x))
out <- .Fortran("foo", x = as.double(x), n = length(x), PACKAGE = "ry4")
return(out$x)
}
<environment: namespace:ry4>