如何在循环中的get()之后保留变量名?

时间:2017-10-07 22:09:49

标签: r for-loop

n <- 1000 
xcat <- sample(x=c("A","B", "C", "D", "E"), 
 size=n, replace=TRUE, prob=rep(1/5, 5))  #(a)
xcont<-rnorm(n,23,4)
dat<-data.frame(xcat,xcont)
for(i in 1:200){
assign(paste('x',i,sep=""),rnorm(n,2+i*2,i))
dat<-cbind(dat,get(paste('x',i,sep="")))
}
names(dat)[1:4]
[1] "xcat"                             "xcont"                            "get(paste(\"x\", i, sep = \"\"))" "get(paste(\"x\", i, sep = \"\"))"

dat中的变量名称不是我想要的(get(粘贴(\&#34; x \&#34;,i,sep = \&#34; \&#34;))&#34 ;&#34; get(粘贴(\&#34; x \&#34;,i,sep = \&#34; \&#34;)))。我想要x1,x2,x3的名称......如何获得数据框的正确名称?

2 个答案:

答案 0 :(得分:0)

将它们命名为“事后”:

n <- 1000 
xcat <- sample(x=c("A","B", "C", "D", "E"), 
 size=n, replace=TRUE, prob=rep(1/5, 5))  
xcont<-rnorm(n,23,4)
dat<-data.frame(xcat,xcont)
for(i in 1:200){

dat<-cbind(dat, rnorm(n,2+i*2,i) )

}
names(dat)[3:202] <- paste('x',1:200,sep="")
names(dat)[1:4]
#[1] "xcat"  "xcont" "x1"    "x2"   

答案 1 :(得分:0)

如果您只想创建新变量,这也应该有效:

JPanel