0

I'm trying to figure out how to iteratively load a matrix (this form part of a bigger function I can't reproduce here).

Let's suppose that I create a matrix:

 m <- matrix(c(1:9), nrow = 3, ncol = 3)
 m

This matrix can be named "m", "x" or whatsoever. Then, I need to load iteratively the matrix in the function:

 if (interactive() ) { mat <- 
     readline("Your matrix, please: ")
 }

So far, the function "knows" the name of the matrix, since mat returns [1] "m", and is a object listed in ls(). But when I try to get the matrix values, for example through x <- get(mat) I keep getting an error

Error in get(mat) : unused argument (mat)

Can anybody be so kind as to tell me what I'm doing wrong here?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
perep1972
  • 147
  • 1
  • 9
  • 2
    Might want to start here, on how to create an empty matrix and it will also give you some clues on how to accomplish your loop. https://stackoverflow.com/questions/21585721/how-to-create-an-empty-matrix-in-r, also `get` doesn't do what you think it does. – Chuck P May 22 '20 at 13:52
  • 1
    loading almost anything iteratively in R is probably going to be the wrong way to approach things. in this case why not just : `x = mat` ? – dvd280 May 22 '20 at 13:55

1 Answers1

1

1) Assuming you mean interactive, not iterative,

get_matrix <- function() {
  nr <- as.numeric(readline("how many rows? "))
  cat("Enter space separated data row by row. Enter empty row when finished.\n")
  nums <- scan(stdin())
  matrix(nums, nr, byrow = TRUE)
}
m <- get_matrix()

Here is a test:

> m <- get_matrix()
how many rows? 3
Enter space separated data row by row. Enter empty row when finished.
1: 1 2
3: 3 4
5: 5 6
7: 
Read 6 items

> m
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
> 

2) Another possibility is to require that the user create a matrix using R and then just give the name of the matrix:

get_matrix2 <- function(envir = parent.frame()) {
  m <- readline("Enter name of matrix: ")
  get(m, envir)
}

Test it:

> m <- matrix(1:6, 3)
> mat <- get_matrix2()
Enter name of matrix: m
> mat
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341