Dynamic Variable naming in r

后端 未结 2 661
执念已碎
执念已碎 2021-02-06 09:26
structure(list(Metrics = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 
1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 
5L, 6L), .Label = c(\"  LINESCOMM \", \"           


        
2条回答
  •  难免孤独
    2021-02-06 10:17

    assign is used by supplying the name of the variable you want to create first and the value it should have as second argument. Note that as your project names contain leading blanks I additionally used str_trim to get rid of them.

    library(stringr)
    projects <- levels(agg$Project)
    for (p in projects) {
      x <- subset(agg, Project==p)
      assign(str_trim(p), x)    
    }
    

    Now you have the projects as variables in your workspace:

    ls()
    [1] "agg"            "Demo_Architect" "Demo_May_10"    "Demo_May_14"    "NPP"           
    [6] "p"              "projects"       "x"
    

    E.g.

    > Demo_Architect
              Metrics           Project    Value
    1      LINESCOMM    Demo_Architect  1172.000
    2   NCNBLOC_FILE    Demo_Architect  1500.000
    3    RCYCLOMATIC    Demo_Architect   142.000
    4           RISK    Demo_Architect     4.241
    5      RMAXLEVEL    Demo_Architect    24.000
    6      RNOEXSTAT    Demo_Architect    98.000
    

提交回复
热议问题