I am pretty ok with loops in Stata and I am trying to program something similar in R, but I keep getting error messages- any idea why this loop doesnt work?
I have an Excel sheet with data with separate tabs for each month (as in monthlist). I want to import each separate tab and add year and month column to it.
monthlist = list("Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec")
for (k in seq_along(monthlist)){
infile <- paste(i, " GP",".xlsx",sep=""); name<-
paste("X",i,"_GP",sep="")
name.[k]<- read_excel(infile, sheet = [k])
month=[k]
name.[k] = cbind(year, month, name.[k])
}
I have tried and tried researching the correct reference to k values, but I cant figure it out. Please help.
If I understand correctly following the comments, I think you want to take data from different sheets across several workbooks, and assign each sheet's data to its own separate dataframe, so that you have many dataframes; and you don't want to do this combining inside the loop because each could be structured differently. If that's the case then you could modify your code to this:
The key points there are to drop the square brackets around
k
when reading in the file, and secondly to useassign()
to dynamically create a variable name.d_temp
temporarily stores the data frame before assign creates a new distinct variable from it.I note references to
year
andi
in your code which I assume you have set beforehand, so I'm not addressing those.