Dynamic Variable naming in r

后端 未结 2 660
执念已碎
执念已碎 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条回答
  •  梦毁少年i
    2021-02-06 10:13

    Why not just splitting the data.frame and working with list

    dflist <- split(agg, agg$Project)
    str(dflist)
    ## List of 4
     ## $   Demo_Architect :'data.frame':   6 obs. of  3 variables:
     ## $   Demo_May_10    :'data.frame':   6 obs. of  3 variables:
     ## $   Demo_May_14    :'data.frame':   6 obs. of  3 variables:
     ## $   NPP            :'data.frame':   6 obs. of  3 variables:
    
    names(dflist) <- paste0("project", seq_along(dflist))
    

    And if you really want to have the list elements (new dfs) in your global environment, you can use list2env.

    list2env(dflist, .GlobalEnv)
    ls()
    ## [1] "agg"      "dflist"   "project1" "project2" "project3"
    ## [6] "project4"
    
    head(project3)
    ##            Metrics        Project    Value
    ## 13      LINESCOMM    Demo_May_14  1172.000
    ## 14   NCNBLOC_FILE    Demo_May_14  1500.000
    ## 15    RCYCLOMATIC    Demo_May_14   142.000
    ## 16           RISK    Demo_May_14     4.241
    ## 17      RMAXLEVEL    Demo_May_14    24.000
    ## 18      RNOEXSTAT    Demo_May_14    98.000
    

    Just want to point out that it's generally safer to work with list by using lapply, sapply or for loop rather than using the global environment.

    EDIT : If you want a different naming scheme

    names(dflist) <- paste0("project_", gsub("\\s+", "", levels(agg$Project)))
    list2env(dflist, .GlobalEnv)
    ls()
    ## [1] "agg"                    "dflist"                
    ## [3] "project_Demo_Architect" "project_Demo_May_10"   
    ## [5] "project_Demo_May_14"    "project_NPP"
    

提交回复
热议问题