Please see the FAQ: What's a reproducible example (`reprex`) and how do I do one? Using a reprex, complete with representative data will attract quicker and more answers.
Here is what happens outside the function
suppressPackageStartupMessages(library(dplyr))
for ( i in 1:5)
{
nam<<-as.name(paste0("mat", i))
gen_sch_mat <<- function(n.row, n.col) t(replicate(n.row, sample(c(rep(0, n.col-1), 1))))
nam <<- gen_sch_mat(5,5)
# print(nam)
} -> exported
exported
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 0 0 0 0 1
#> [2,] 0 0 1 0 0
#> [3,] 0 0 0 1 0
#> [4,] 0 0 1 0 0
#> [5,] 0 0 0 1 0
Created on 2020-03-31 by the reprex package (v0.3.0)
One of the difficulties that experienced programmers frequently encounter is carrying over a procedural/imperative mindset into R
, which just doesn't have a comfortable home for. Whenever more than trivial imperative style programming is called for, it's done natively in a C
and brought in.
R
is more like Haskell
in the way it presents to users
rather than programmers
, it's a functional
language, just like school algebra: f(x) = y.
Let's work backwards.
Last: Use a function pluck an object from another object
Use a function to place objects into another object
Find a function to generate the underlying object
The pieces are all here.
suppressPackageStartupMessages(library(purrr))
# make the names
nams <- paste0("mat",seq(1:5))
# make function to fill a 5x5 matrix with random 1/0s
fill5 <- function(x) {matrix(sample(c(1,0),25,replace = TRUE), nrow = 5, ncol = 5)}
# create the five matrices and assign them to a list called mats
map(nams,fill5) -> mats
# extract the fifth
mats[[5]]
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 1 1 0 0
#> [2,] 0 0 0 1 0
#> [3,] 1 1 1 0 1
#> [4,] 1 0 1 0 1
#> [5,] 1 0 1 0 0
Created on 2020-03-31 by the reprex package (v0.3.0)