简体   繁体   中英

How to assign a value to a matrix created with assign() in R

m <- "mData"
assign(m, matrix(data = NA, nrow = 4, ncol = 5))

Now I want to use variable m to assign values to the mData matrix

assign(m[1, 2], 35) will not work.

Any solution will be much appreciated?

I'm kind of ashamed to post this but there would be a way to do this. It feels so wrong because the R-way would be to build a list of matrices and then operate on them by passing a function to transform them using lapply.

assign.by.char <- function(x,  ...) {
   eval.parent(assign(x,  do.call(`[<-`, list(get(x) , ...)))) }

assign.by.char(m, 1,2,35)
     [,1] [,2] [,3] [,4] [,5]
[1,]   NA   35   NA   NA   NA
[2,]   NA   NA   NA   NA   NA
[3,]   NA   NA   NA   NA   NA
[4,]   NA   NA   NA   NA   NA

If you really need to use assign() , you could do it with replace()

m <- matrix(, 3, 3)
assign("m", replace(m, cbind(1, 2), 35))
m
#      [,1] [,2] [,3]
# [1,]   NA   35   NA
# [2,]   NA   NA   NA
# [3,]   NA   NA   NA

Or you can use assign directly (a variant of @BondedDust's solution)

 assign(m, `[<-`(get(m), cbind(1,2), 35))
 mData
 #     [,1] [,2] [,3]
 #[1,]   NA   35   NA
 #[2,]   NA   NA   NA
 #[3,]   NA   NA   NA

Or as a function

assign.by.char <- function(x, ...){
  eval.parent(assign(x, `[<-`(get(x), ...)))}

data

mData <- matrix(, 3, 3)
 m <- 'mData'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM