R get() function error

后端 未结 2 648
情书的邮戳
情书的邮戳 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.

    0 讨论(0)
  • 2021-01-19 16:36

    Use function assign instead of get:

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

    get returns an object's value, assign assigns. :)

    Same thing with eval, it just evaluates your call.

    0 讨论(0)
提交回复
热议问题