{"id":22225463,"url":"https://github.com/beliavsky/r_and_fortran","last_synced_at":"2025-03-25T08:22:02.688Z","repository":{"id":258394907,"uuid":"870679526","full_name":"Beliavsky/R_and_Fortran","owner":"Beliavsky","description":"Examples of simple R and Fortran programs that calculate descriptive statistics and of equivalent R and Fortran syntax","archived":false,"fork":false,"pushed_at":"2024-11-22T14:04:05.000Z","size":57,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-30T07:42:40.727Z","etag":null,"topics":["fortran","fortran-tutorial","language-comparison","r","r-tutorial","simulation","statistics"],"latest_commit_sha":null,"homepage":"","language":"Fortran","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Beliavsky.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-10T13:26:53.000Z","updated_at":"2024-11-22T14:04:08.000Z","dependencies_parsed_at":"2024-10-18T20:03:26.522Z","dependency_job_id":"12662ba1-a6b1-4b25-9ed2-dd6d18e589cd","html_url":"https://github.com/Beliavsky/R_and_Fortran","commit_stats":null,"previous_names":["beliavsky/r_and_fortran"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Beliavsky%2FR_and_Fortran","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Beliavsky%2FR_and_Fortran/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Beliavsky%2FR_and_Fortran/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Beliavsky%2FR_and_Fortran/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Beliavsky","download_url":"https://codeload.github.com/Beliavsky/R_and_Fortran/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245423883,"owners_count":20612858,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fortran","fortran-tutorial","language-comparison","r","r-tutorial","simulation","statistics"],"created_at":"2024-12-03T00:17:55.492Z","updated_at":"2025-03-25T08:22:02.667Z","avatar_url":"https://github.com/Beliavsky.png","language":"Fortran","funding_links":[],"categories":[],"sub_categories":[],"readme":"# R and Fortran\n\nHere are some R and Fortran code equivalents, with the R code listed first. The R and Fortran comment characters are `#` and `!`.\n### sequence\n```R\n# R\n-2:3 # -2 -1 0 1 2 3\n```\n```Fortran\n! Fortran\ninteger :: i\n[(i, i=-2, 3)] ! implied do-loop\n```\n### repeat a value\n```R\n# R\nrep(2, 3) # 2 2 2\n```\n```Fortran\n! Fortran\ninteger :: i\n[(2, i=1, 3)]\n```\n### loops, conditionals, and output\n```R\n# R\nfor (i in -1:1) {\n\tif (i \u003e 0) {\n\t  cat(i, \"positive\\n\") # \\n is needed to get a new line after the output\n\t} else if (i == 0) {\n\t  cat(i, \"zero\\n\")\n\t} else {\n\t  cat(i, \"negative\\n\")\n\t}\n}\n```\n```Fortran\n! Fortran\nimplicit none\ninteger :: i\ndo i=-1,1\n   if (i \u003e 0) then\n      print*,i, \"positive\"\n   else if (i == 0) then\n      print*,i, \"zero\"\n   else\n      print*,i, \"negative\"\n   end if\nend do\nend\n```\n### while loop\n```R\n# R\nsum = 0\ni = 0\nwhile (sum \u003c= 10) {\n  i = i + 1\n  sum = sum + i\n}\ncat(\"Sum of 1 to\", i, \"is\", sum, \"\\n\")\n# output:\n# Sum of 1 to 5 is 15\n```\n```Fortran\n! Fortran\ninteger :: i, isum\nisum = 0\ni = 0\ndo while (isum \u003c= 10)\n   i = i + 1\n   isum = isum + i\nend do\nprint*,\"Sum of 1 to\", i, \"is\", isum\nend\n```\n### exponentiation\n```R\n# R\n2^3, 2**3 # ^ is preferred, but both are valid\n```\n```Fortran\n! Fortran\n2**3\n```\n### create array\n```R\nv = c(2, 4, 6) # R create array of 3 floats\nv = c(2L, 4L, 6L) # create array of 3 integers\n```\n```Fortran\n! Fortran\ninteger, allocatable :: v(:)\nv = [2, 4, 6]\n```\n### matrix transpose\n```R\n# R\nt(x)\n```\n```Fortran\n! Fortran\ntranspose(x)\n```\n### matrix multiplication\n```R\n# R\na %*% b\n```\n```Fortran\n! Fortran\nmatmul(a, b)\n```\n### dot product\n```R\n# R\na %*% b\n```\n```Fortran\n! Fortran\ndot_product(a, b)\n```\n### access array element\n```R\nv[2, 1, 5] # R\n```\n```Fortran\nv(2, 1, 5) ! Fortran\n```\n### negative indices\nThe lower bounds of R arrays are always 1. A negative array index means that the index is excluded.\n```R\n# R\nx = c(10, 20, 30)\ncat(x[-2], \"\\n\")\n# output:\n# 10 30\n```\nFortran arrays have lower bounds of 1 by default, but this can be overridden. A negative index has no special meaning.\n### size of array\n```R\nlength(v) # R\n```\n```Fortran\nsize(v) ! Fortran\n```\n### dimensions of array\n```R\ndim(v) # R\n```\n```Fortran\nshape(v) ! Fortran\n```\n### sum of array\n```R\nsum(v) # R -- same in Fortran\n```\n### product of array\n```R\nprod(v) # R\n```\n```Fortran\nproduct(v) ! Fortran\n```\n### maximum and minimum of array\n```R\nmax(v), min(v) # R\n```\n```Fortran\nmaxval(v), minval(v) ! Fortran\n```\n### location of maximum and minimum of array\n```R\n# R\nv = c(3, 8, 2, 10, 5)\ncat(which.max(v), which.min(v), \"\\n\")\n# output:\n# 4 3\n```\n```Fortran\n! Fortran\ninteger :: v(5)\nv = [3, 8, 2, 10, 5]\nprint*,maxloc(v, dim=1), minloc(v, dim=1)\nend\n``` \n### select elements satisfying a condition\n```R\nv[v \u003e 3] # R: select elements of v exceeding 3\n```\n```Fortran\npack(v, v \u003e 3) ! Fortran\n```\n### select the first row or column of a 2-D array\n```R\nx[1, ] # R: 1st row\nx[, 1] # 1st column\n```\n```Fortran\nx(1, :) ! Fortran: 1st row\nx(:, 1) ! 1st column\n```\n### create array of zeros\n```R\nx = array(0.0, c(5, 6, 7)) # R: create 3-D array of dimensions [5, 6, 7] and set values to 0.0\n```\n```Fortran\n! Fortran\nreal(kind=dp), allocatable :: x(:, :, :) ! dp is a double precision kind parameter\nallocate(x(5, 6, 7), source = 0.0_dp)\n```\n### choose a value\n```R\nifelse(condition, 3, 4) # R: return 3 if condition is TRUE, otherwise 4\n```\n```Fortran\nmerge(3, 4, condition) ! Fortran\n```\n### Boolean variables and operators: (! \u0026 |) in R, (.not. .and. .or.) in Fortran\n```R\n# R\nx = TRUE\ny = FALSE\ncat(x, y, !x, !y, x \u0026 y, x | y, \"\\n\")\n# output:\n# TRUE FALSE FALSE TRUE FALSE TRUE\n```\n```Fortran\n! Fortran\nlogical :: x, y\nx = .true.\ny = .false.\nprint*, x, y, .not. x, .not. y, x .and. y, x .or. y\nend\n! output:\n! T F F T F T\n```\n### concatenate strings\n```R\n# R\npaste(\"ab\", \"cd\") # gives \"ab cd\"\npaste0(\"ab\", \"cd\") # gives \"abcd\"\n```\n```Fortran\n! Fortran\n\"ab\" // \" \" // \"cd\"\n\"ab\" // \"cd\"\n```\n### complex numbers\n```R\n# R\n3.0 + 4.0i\n```\n```Fortran\n! Fortran\n(3.0d0, 4.0d0) ! d0 is used to give double precision, matching R\n```\n### complex conjugate\n```R\n# R\nConj(z) # note capitalization\n```\n```Fortran\n! Fortran\ncongj(z)\n```\n### define and call a function\n```R\n# R\ntwice \u003c- function(x) {\n  return(2 * x)\n}\ncat(twice(c(3.0, 4.0)), \"\\n\")\n# output\n# 6 8\n```\n```Fortran\n! Fortran\nelemental real function twice(x)\n! elemental means the function can take a scalar or array input and return the same, like the R function\nreal, intent(in) :: x\ntwice = 2*x\nend function twice\nprint*,twice([3.0, 4.0])\nend\n```\n### create a constructor for a new data type and a function that acts on it\n```R\n# R\n# Define a constructor function for the class RightTriangle\nRightTriangle = function(x, y) {\n  return(list(x = x, y = y))  # Create a list with attributes\n}\n# Define the hypotenuse method\nhypotenuse = function(a) {\n\treturn(sqrt(a$x^2 + a$y^2))\n}\n# Invoke it on an instance of RightTriangle\ncat(hypotenuse(RightTriangle(1.5, 2.0)), \"\\n\") # output: 2.5\n```\n```Fortran\n! Fortran\nprogram main\nimplicit none\n! define type RightTriangle\ntype :: RightTriangle\n   real :: x, y\nend type\nprint*,hypotenuse(RightTriangle(1.5, 2.0)) ! output: 2.5\ncontains\n! define hypotenuse function acting on type\nreal function hypotenuse(tri)\ntype(RightTriangle) :: tri\nhypotenuse = sqrt(tri%x**2 + tri%y**2)\nend function\nend program main\n```\n### import from R library or Fortran module\n```R\nlibrary(foo) # R\n```\n```Fortran\nuse foo ! Fortran\n```\nThis repo has simple R and Fortran programs that compute the means and variances of sets of uniform random variates and\nsome statistics on those quantities.\n\nSample R output of `xsim_uniform.r`:\n\n```\n    Number of observations per data set:            100\n    Number of data sets:                        1000000\n    Average Mean:                                    0.5000192068\n    Average Variance:                                0.0833360355\n    Standard Error of Mean:                          0.0000288673\n    Standard Error of Variance:                      0.0000075392\n    Minimum Mean:                                    0.3677907574\n    Maximum Mean:                                    0.6419923536\n    Minimum Variance:                                0.0501358999\n    Maximum Variance:                                0.1214716295\n```\n\nSample Fortran output of `xsim_uniform.f90`:\n\n```\n    Number of observations per data set:       100\n                    Number of data sets:   1000000\n                Average Mean           :        0.4999585642\n                Average Variance       :        0.0833183208\n                Standard Error of Mean :        0.0000288502\n             Standard Error of Variance:        0.0000075364\n                Minimum Mean           :        0.3597154884\n                Maximum Mean           :        0.6331273418\n                Minimum Variance       :        0.0478706009\n                Maximum Variance       :        0.1232975046\n```\nOn my Windows PC, the Fortran program compiled with `gfortran -O3 -march=native` takes 0.9s, and the R program takes 14s.\n\nThe module `r.f90` defines some Fortran functions that emulate those of R. Compiling with `gfortran r.f90 xr.f90` and running gives\n\n```\n                    Real data:     1.0000     2.0000     3.0000     4.0000     5.0000     6.0000     7.0000     8.0000     9.0000    10.0000\n                 Integer data:          1          2          3          4          5          6          7          8          9         10\n            Mean of real_data:     5.5000\n             Mean of int_data:     5.5000\nStandard deviation of real_dat     3.0277\nStandard deviation of int_data     3.0277\n        Variance of real_data:     9.1667\n         Variance of int_data:     9.1667\n          Median of real_data:     5.5000\n           Median of int_data:     5.5000\n           Range of real_data:     1.0000    10.0000\n            Range of int_data:          1         10\n       Quantiles of real_data:     3.2500     5.5000     7.7500\n        Quantiles of int_data:     3.2500     5.5000     7.7500\n             IQR of real_data:     4.5000\n              IQR of int_data:     4.5000\n         Product of real_data:   3628800.0000\n          Product of int_data:    3628800\n```\n\nand running the R script `xr.r` gives the same results:\n\n```\n                       Real data:     1.0000     2.0000     3.0000     4.0000     5.0000     6.0000     7.0000     8.0000     9.0000    10.0000 \n                    Integer data:          1          2          3          4          5          6          7          8          9         10 \n               Mean of real_data:     5.5000 \n                Mean of int_data:     5.5000 \n Standard deviation of real_data:     3.0277 \n  Standard deviation of int_data:     3.0277 \n           Variance of real_data:     9.1667 \n            Variance of int_data:     9.1667 \n             Median of real_data:     5.5000 \n              Median of int_data:     5.5000 \n              Range of real_data:     1.0000    10.0000 \n               Range of int_data:          1         10 \n          Quantiles of real_data:     3.2500     5.5000     7.7500 \n           Quantiles of int_data:     3.2500     5.5000     7.7500 \n                IQR of real_data:     4.5000 \n                 IQR of int_data:     4.5000 \n            Product of real_data: 3628800.0000 \n             Product of int_data:    3628800\n```\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbeliavsky%2Fr_and_fortran","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbeliavsky%2Fr_and_fortran","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbeliavsky%2Fr_and_fortran/lists"}