从子程序输出到 R 中获取 n 维 Fortran 数组?

get n dimensional 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)         :: X

    X = DF(:,d)+DF(:,d)

end subroutine test

我能够为 R 加载它并 运行 编译它。但是我得到的不是一个数组,而是一个数字。

system("R CMD SHLIB ./Fortran/mytest.f90")
dyn.load("./Fortran/mytest.so")

input <- data.frame(A=c(11,12), B=c(21, 22))
.Fortran("test", d = as.integer(1), i = nrow(input), nMCd = ncol(input), DF = unlist(input), X = as.numeric(1))

我做错了什么?!

我的输出看起来像

$d
[1] 1

$i
[1] 2

$nMCd
NULL

$DF
A1 A2 B1 B2 
11 12 21 22 

$X
[1] 22

这个的 R 版本是:

input[,1]+input[,1]

我还没有弄清楚这应该做什么,因为我没有用 FORTRAN 编程(而且你没有用我读过的语言说出你的期望)但这是一个实验输入对象第一列中项目的总和,当我查看带有输入的代码时,这可能有些意义。发送 1 for d 以从 DF(:,d)+ DF(:,d) 中提取似乎可能意味着您想要第一列的总和。请注意,我刚刚向 X 提供了一个空的 4 元素向量,并使其 Fortran 维度与 DF:

相同

文件中的来源:

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(i)

    X = DF(:,d)+DF(:,d)

end subroutine test

R代码:

input <- data.frame(A=c(11,12), B=c(21, 22))
.Fortran("test", d = as.integer(1), i = nrow(input), nMCd = ncol(input),
                      DF = unlist(input), X = numeric(4))
#--- result------
$d
[1] 1

$i
[1] 2

$nMCd
[1] 2

$DF
A1 A2 B1 B2 
11 12 21 22 

$X
[1] 22 24  0  0

进一步实验,仍然不了解 Fortran,尝试将第一行中的项目加在一起:

  X = DF(d,:)+DF(d,:)

出品:

 $X
 [1] 22 42  0  0