Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R get() function error

Tags:

r

I'm trying to populate a set of matrices where the matrix (object) names are held in a list. I can use the get() to return the object with the given name, but I'm running into function problems when I use get() to define the matrix object I'm trying to populate.

#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'm getting 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 'could not find function' error when I try to populate the matrix.

Could someone explain the error in my approach, here?

Edit/Update:

So in my attempt to simplify the question for posting here, I realized that I may have oversimplified what I'm attempting to do.

So, in fact, I'm attempting to populate elements within a set of matricies. The names of the matrices are contained in the list.names object. I'm using nested for() loops to populate each element within the matrices.

So, in fact, my problem would be more accurately stated as:

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

A couple of the replies have suggested that I use assign based upon my original post, but given that I'm attemping to 'assign' an element within the object rather than the whole object , this approach won't work.

Sorry for the confusion.

like image 391
user2059737 Avatar asked Feb 18 '23 06:02

user2059737


1 Answers

This is addressed in FAQ 7.21. The most important part of that FAQ is the end where it says to use a list (a real list, not the vector that you are calling a list above). A lot of things become much easier if you have a list of matricies instead of a bunch of matricies in your global work space. 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 much simpler than messing around with get and assign.

like image 155
Greg Snow Avatar answered Feb 19 '23 20:02

Greg Snow