从子程序输出到 R 中获取矩形 Fortran 数组?
get rectangular Fortran array from subroutine output into R?
这是 的跟进。不同之处在于,我想要的不是一维数组,而是二维数组。
我有以下 Fortran 子例程:
subroutine test(d, i, nMCd, DF, X)
integer, intent(in) :: d, i, nMCd
double precision, intent(in), dimension(i,nMCd) :: DF
double precision, intent(out), dimension(i,nMCd) :: X
X = DF + DF
end subroutine test
在 R 中,代码很简单:
input <- data.frame(A=c(11,12), B=c(21, 22))
input + input
我得到一个 2 x 2 数据框
我能够为 R 加载它并 运行 它进行编译。
system("R CMD SHLIB ./Fortran/mytest.f90")
dyn.load("./Fortran/mytest.so")
X <- .Fortran("test", d = as.integer(1), i = nrow(input), nMCd = ncol(input), DF = unlist(input), X = numeric(nrow(input)*ncol(input)))$X
但我得到的是长度为 4 的向量,而不是 2x2 矩阵或数据框。我尝试了 X = numeric(nrow(input), ncol(input))
但它不起作用
我能想到的唯一解决方案是在 运行 fortran 函数
之后 运行ning
matrix(X,nrow = nrow(input),ncol = ncol(input))
谢谢!
我查看了 .Fortran
、.Call
和 "Writing R extensions" 的文档,但没有发现 Fortran 子例程 returns 矩阵的任何实例。此外,?.Fortran
帮助页面中没有矩阵类型,所以我认为我的评论可能是最好的解决方案:
in R you can also coerce a vector to matrix by adding a dimension: dim(X) <- c(2,2).
Or even with more generality: dim(X) <- dim(input)
显然我不能声称这是来自高权威,因为我以前没有做过任何 Fortran 编程。如果您有兴趣编写与 R 对象就地交互的代码,您可能需要考虑研究 data.table
包的代码。大多数此类工作都使用 C 或 C++。您还可以考虑 Rcpp 或内联包接口。 Fortran 接口主要用于利用许多经过验证的数值函数。
这是
我有以下 Fortran 子例程:
subroutine test(d, i, nMCd, DF, X)
integer, intent(in) :: d, i, nMCd
double precision, intent(in), dimension(i,nMCd) :: DF
double precision, intent(out), dimension(i,nMCd) :: X
X = DF + DF
end subroutine test
在 R 中,代码很简单:
input <- data.frame(A=c(11,12), B=c(21, 22))
input + input
我得到一个 2 x 2 数据框
我能够为 R 加载它并 运行 它进行编译。
system("R CMD SHLIB ./Fortran/mytest.f90")
dyn.load("./Fortran/mytest.so")
X <- .Fortran("test", d = as.integer(1), i = nrow(input), nMCd = ncol(input), DF = unlist(input), X = numeric(nrow(input)*ncol(input)))$X
但我得到的是长度为 4 的向量,而不是 2x2 矩阵或数据框。我尝试了 X = numeric(nrow(input), ncol(input))
但它不起作用
我能想到的唯一解决方案是在 运行 fortran 函数
之后 运行ningmatrix(X,nrow = nrow(input),ncol = ncol(input))
谢谢!
我查看了 .Fortran
、.Call
和 "Writing R extensions" 的文档,但没有发现 Fortran 子例程 returns 矩阵的任何实例。此外,?.Fortran
帮助页面中没有矩阵类型,所以我认为我的评论可能是最好的解决方案:
in R you can also coerce a vector to matrix by adding a dimension: dim(X) <- c(2,2).
Or even with more generality: dim(X) <- dim(input)
显然我不能声称这是来自高权威,因为我以前没有做过任何 Fortran 编程。如果您有兴趣编写与 R 对象就地交互的代码,您可能需要考虑研究 data.table
包的代码。大多数此类工作都使用 C 或 C++。您还可以考虑 Rcpp 或内联包接口。 Fortran 接口主要用于利用许多经过验证的数值函数。