get n dimensional Fortran array from subroutine output into R?

烈酒焚心 提交于 2019-12-25 01:33:53

问题


I have the following Fortran subroutine:

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

I am able to compile it for R load it and run it. But instead of getting an array I'm getting a single number.

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

What am I doing wrong?!

My output looks like

$d
[1] 1

$i
[1] 2

$nMCd
NULL

$DF
A1 A2 B1 B2 
11 12 21 22 

$X
[1] 22

The R version of this is:

input[,1]+input[,1]

回答1:


I haven't figured out what this was supposed to do because I don't program in FORTRAN (And you didn't say what you expected in a language that I do read) but this is an experiment that delivers the sum of the items in the first columns of the input object, which might make some sense when I look at the code with the inputs. It seems possible that sending 1 for d to extract from DF(:,d)+ DF(:,d) might mean you wanted the sums of first columns. Notice that I just supplied an empty 4 element vector to X and made its Fortran dimensions the same as DF:

Source in file:

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 code:

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

Further experiment, still without any knowledge of Fortran, trying to add the items in the first row together:

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

Produced:

 $X
 [1] 22 42  0  0


来源:https://stackoverflow.com/questions/31572566/get-n-dimensional-fortran-array-from-subroutine-output-into-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!