Error function R get ()

I am trying to populate a set of matrices in which the names of the matrices (objects) are stored in a list. I can use get () to return the object with the given name, but when I use get () to determine the matrix, the object I'm trying to fill is.

#Create list of matrix names: list.names <- c("m.1") #Create matrix object m.1 <- matrix(nrow=2,ncol=2) #Return matrix m.1 from the list.names using get(). Works great! get(list.names[1]) #Populate m.1 with some values. Doesn't work. get(list.names[1]) <- c(1,2,3,4) 

So, in the last line of code, I get an error:

could not find function "get <-"

Similarly, I can call m.1 using:

 eval(as.name(list.name[1])) 

But R returns a similar error "could not find function" when I try to fill the matrix.

Can someone explain the error in my approach here?

Change / Update:

Therefore, trying to simplify the issue for publication here, I realized that maybe I simplified what I'm trying to do.

So, actually, I'm trying to populate the elements in a matrix set. Matrix names are contained in the list.names object. I use nested for () loops to populate each element in the matrices.

So, in fact, my problem will be more accurately indicated as:

 get(list.names[1])[1,1] <- some_value 

Several answers suggested using an assignment based on my original post, but given that I'm trying to “assign” an element within an object, not the whole object, this approach will not work.

Sorry for the confusion.

+3
source share
2 answers

Use the assign function instead of get :

 assign(list.names[1],c(1,2,3,4)) 

get returns the value of the object, assign assigns. :)

Same with eval , it just evaluates your call.

+3
source

This is described in FAQ 7.21. The most important part of this FAQ is the end, which says that you need to use a list (a real list, not the vector that you call in the list above). Much becomes much easier if you have a list of matrices, and not a bunch of matrices in your global workspace. Here is an example:

 mnames <- c('m.1','m.2','m.3') m.1 <- matrix(1, 2, 2) m.2 <- matrix(2, 2, 2) m.3 <- matrix(3, 2, 2) ## put matricies into a list mymats <- lapply( mnames, get ) names(mymats) <- mnames ## change 1 value in each matrix a different way mymats[['m.2']][1,1] <- 22 mymats[[1]][2,2] <- 11 tmp <- "m.3" mymats[[tmp]][1,2] <- 33 ## change the same element in each matrix using a loop for( i in seq_along(mymats) ) { mymats[[i]][2,1] <- 44 } ## apply the same function to every matrix and simplify the output sapply( mymats, rowMeans ) 

This is a lot easier than messing with get and assign .

+3
source

Source: https://habr.com/ru/post/1209160/


All Articles