所有括号都关闭 - 但这个循环不会运行

时间:2015-04-18 16:56:06

标签: r loops dataframe

尝试为我可重复的示例组合一个循环。

for (i in c(2006,2008,2010,2012)) {
UniqueID <- 1:10 # <- Not all numeric - Kept as character vector
Name <- LETTERS[seq( from = 1, to = 10 )]
Entity_Type <- factor("This","That")
Data1 <- rnorm(10)     
Data2 <- rnorm(10) 
Data3 <- rnorm(10) 
Data4 <- rnorm(10) 
Year <- i
x[i] <- data.frame(UniqueID, Name, Entity_Type, Data1, Data2, Data3, Data4, Year)
}

现在错误是:

 Error in `[<-.data.frame`(`*tmp*`, i, value = list(UniqueID = 1:10, Name = 1:10,  : 
  new columns would leave holes after existing columns 

我如何格式化它以便它可以获取年份的值?

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为不可能将数据框放在向量中,你必须使用list。

 x <- list()
 years <- c(2006,2008,2010,2012)

 for (i in 1:length(years)) {
  UniqueID <- 1:10 # <- Not all numeric - Kept as character vector
  Name <- LETTERS[seq( from = 1, to = 10 )]
  Entity_Type <- factor("This","That")
  Data1 <- rnorm(10)     
  Data2 <- rnorm(10) 
  Data3 <- rnorm(10) 
  Data4 <- rnorm(10) 
  Year <- years[i]
  x[[i]] <- data.frame(UniqueID, Name, Entity_Type, Data1, Data2, Data3, Data4, Year)
 }