0

I am generating a large quantity of product specific tables based on information compiled from several other tables. Because of the quantity of product tables that I will be creating, their names are generated. I am looking to assign vector values by using a string, rather than the specific name of the object. Eventually I will have to reference by a for loop.

product<-list("A", "B", "C")
assign(paste(product[3],"_gen", sep=""), as.data.frame(matrix(nrow=3, ncol=5)))

from this the matrix has been created. I am looking to reference the original string to change specific vectors. I would like to change C_gen[3,2] to a value of 5 using the original paste reference. I've failed different ways using the <- and assign() functions, but probably the best way to show the basis of what I am trying to do is with:

paste(product[3],"_gen", sep="")[3,2]<- 5
faiien
  • 3
  • 3
  • 1
    Why not use `sapply` with `USE.NAMSE = TRUE` and `simplify = FALSE` to create a named list object containing our matrices. Probably a better idea than jamming up your global environment with a bunch of named matrices. Then you can use the apply functions to iterate over the matrices and do other calculations after. – dayne Jul 27 '16 at 20:04

1 Answers1

0

One way to do what you ask is to generate the calls yourself, then just evaluate the calls in the global environment. Please read ?call and take a look at this site.

## Create two matrices, "mat1" and "mat2"
mat1 <- matrix(1:10, ncol = 2)
mat2 <- matrix(1:10, ncol = 2)

## Need a vector of the matrix names 
nms <- c("mat1", "mat2")

## Create a function to generate calls
mkCall <- function(x) call("<-", call("[", as.name(x), 1, 2), 100)

## Create and evaluate calls
calls <- lapply(nms, mkCall)
sapply(calls, eval, envir = globalenv())

Another approach is to use parse to transform strings into expressions, as shown in this answer.

calls2 <- paste0(nms, "[1, 2] <- 150")
calls2 <- lapply(calls, function(x) parse(text = x))
sapply(calls2, eval, envir = globalenv())

For the problem you roughly outlined, I still think it would be much better to go back and generate the original matrices using sapply then accessing the individual matrices using [[.

Community
  • 1
  • 1
dayne
  • 7,504
  • 6
  • 38
  • 56