R get() function error

后端 未结 2 647
情书的邮戳
情书的邮戳 2021-01-19 16:12

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

2条回答
  •  北海茫月
    2021-01-19 16:35

    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.

提交回复
热议问题