Name list elements based on variable names R

前端 未结 1 588
遥遥无期
遥遥无期 2021-01-18 03:59

I want to add elements to an empty list on the fly. Each element in the list should be named automatically after a set of variables which value will vary.

However,

相关标签:
1条回答
  • 2021-01-18 04:20

    You cannot assign to paste() using the <- operator (and I believe this is true for the eval() function as well). Instead, you need to either use the [[ operator or use the names() function. You can do this like so:

    L <- list()
    var1 <- "wood"
    var2 <- 1.0
    var3 <- "z4"
    varname <- paste(var1, as.character(var2), var3, sep="_")
    
    # Using [[
    L[[varname]] <- c(0,1)
    
    > L
    $wood_1_z4
    [1] 0 1
    
    # Using names()
    L[[1]] <- c(0,1)
    names(L)[1] <- varname
    
    > L
    $wood_1_z4
    [1] 0 1
    

    A more effective way to do this might be to use a function that both creates the value and names the list element, or even one that just creates the value - if you then use sapply you can name each list element using arguments from the call to your function and the USE.NAMES options.

    In a general sense, R isn't really well-optimized for growing lists over time when the final size and structure of the list aren't well-known. While it can be done, a more "R-ish" way to do it would be to figure out the structure ahead of time.

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