R中的动态变量命名 [英] Dynamic Variable naming in r
问题描述
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 ", " NCNBLOC_FILE ", " RCYCLOMATIC ",
" RISK ", " RMAXLEVEL ", " RNOEXSTAT "), class = "factor"),
Project = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L
), .Label = c(" Demo_Architect ", " Demo_May_10 ", " Demo_May_14 ",
" NPP "), class = "factor"), Value = c(1172, 1500, 142,
4.241, 24, 98, 1139, 1419, 128, 3.546, 22, 85, 1172, 1500,
142, 4.241, 24, 98, 115008, 148903, 14539, 105.914, 604,
15710)), .Names = c("Metrics", "Project", "Value"), row.names = c(NA,
-24L), class = "data.frame")->agg
我正在尝试:
要为每个唯一的项目名称创建包含所需值的单独变量名称。
I am trying to do: For each unique project name is want create separate variable name containing the desired values.
我正在尝试以下代码:
x=data.frame()
attach(agg)
r<-as.character(unique(Project))
for(i in length(agg))
{
x<-subset(agg,Project==r[i],select=c("Project","Metrics","Value"))
assign() #This is where i am making mistake while creating dynamic variable naming
}
换句话说,每次for循环时我想创建一个单独的变量名
in other words i want to create separate variable name each time the for loop executes.
注意:最好将变量名以 project列值的名称命名。
NOTE: it is preferred to have variable names to be in the name of "project"columns values.
推荐答案
assign
用于提供要首先创建的变量的名称以及该变量应作为第二个参数使用的值。请注意,由于您的项目名称包含前导空格,因此我另外使用了 str_trim
来消除它们。
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"
例如
> 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
这篇关于R中的动态变量命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!