How to rename element's list indexed by a loop in R

前端 未结 3 1977
你的背包
你的背包 2020-12-10 11:35

I\'m new on R language and I still have a lot to learn. I\'ve a list W of J elements and I would like to rename its elements W[[i]] with Wi

相关标签:
3条回答
  • 2020-12-10 11:44
    names(W) <- paste0("W", seq_along(W))
    

    should do the trick.

    Note that paste0 was introduced in R 2.15 as a "slightly more efficient" version of paste(..., sep = "", collapse) . If you are using an earlier version of R, you can achieve the same using paste:

    names(W) <- paste("W", seq_along(W), sep = "")
    
    0 讨论(0)
  • 2020-12-10 11:44

    Alternatively you can use sprintf():

     w<-list(a="give",b="me an",c="example")
     names(w)<-sprintf("W%i",1:length(w))
    

    As you can see, you do not need a loop for this.

    It should do the work. In this example, the names are W1,W2 and W3

    print(w)
    $W1
    [1] "give"
    
    $W2
    [1] "me an"
    
    $W3
    [1] "example"
    
    0 讨论(0)
  • 2020-12-10 11:52

    A purrr solution using @Quentin's data:

    library(purrr)
    w <- list(a = "give", b = "me an", c = "example") %>% 
      set_names(~paste0("W", 1:length(w)))
    w
    # $W1
    # [1] "give"
    
    # $W2
    # [1] "me an"
    
    # $W3
    # [1] "example"
    
    0 讨论(0)
提交回复
热议问题