-3

Trying to put together a loop for my reproducible example.

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)
}

and now the error is:

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

How can I format this so that it can take that value for the year?

Thanks!

Ximinez
  • 23
  • 5
  • 2
    I think you mean `Year <- i`. You should only use square brackets for sub-setting. – csgillespie Apr 18 '15 at 16:59
  • Thanks! That fixed that part, but now it pops out a different error in creating each separate data frame. – Ximinez Apr 18 '15 at 17:06
  • What is `x`? Please make sure your example is [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). If it's a list, you most likely need `x[[i]]<-`. Plus, this basically completely changes your original question because it's an entirely different problem. You shouldn't make edits that completely change questions. – MrFlick Apr 18 '15 at 17:15
  • Sorry. csgillespie fixed my first, very simple mistake. After that was fixed, the next executable part didn't clear. I'm trying to make 4 data frames each with a different year variable and name – Ximinez Apr 18 '15 at 17:29

1 Answers1

1

I think it is not possible to put data frame in vector, you have to use 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)
 }
Kamil S Jaron
  • 494
  • 10
  • 23
  • This seems to create a list of four data frames within x. I'm trying to create four separate data frames. But it is certainly looking and doing better than what I put together. – Ximinez Apr 18 '15 at 17:38