Reputation: 3
I am trying to create a loop, which produces new tables on each loop, I want each table to be called table_loopnumber, and they will need to look at the table created in the previous loop.
I've tested this code for I=1 and it works fine, but it doesn't work as a loop. Any help would be appreciated, as I am very new to R.
for(i in 1:2) {
proj4810_op_iteration_[i+1]<-setDT(proj4810_op_iteration_i[, list(Median_High = median(unlist(.SD), na.rm = TRUE)),
by = list(item1, section,RL_Description_Full,
seed_dept,
Total_DOD,
england_DoD,
scotland_DoD,
wales_DoD,
IOM_DoD,
NI_DoD,
unknown_DoD,
turnover,
baskets,
items,
unit_price,
Ambient_Low,
Bakery_Low ,
Cleaning_Low,
FTN_Low,
Fresh_Low,
FrozPrep_Low,
current_seedprod)])
}
Thanks in advance
Upvotes: 0
Views: 1401
Reputation: 321
you can "Assign a value to a name in an environment" using assign
. It takes as a first argument "a variable name, given as a character string." and as the second argument the object you want to assign to that variable name. See ?assign
. The opposite (get an object based on its name is get
). Hence, the following should work:
for(i in 1:2){
previous <- get(paste0("proj4810_op_iteration_", i-1) # get previous data table
tmp<-setDT(previous[, list(Median_High = median(unlist(.SD), na.rm = TRUE)),
by = list(item1, section,RL_Description_Full,seed_dept,Total_DOD,england_DoD,scotland_DoD,
wales_DoD,IOM_DoD,NI_DoD,unknown_DoD,turnover,baskets,items, unit_price,
Ambient_Low, Bakery_Low ,Cleaning_Low, FTN_Low, Fresh_Low, FrozPrep_Low,
current_seedprod)])
vname <- paste0("proj4810_op_iteration_", i) # name of object to be created # name of the current data table
assign(vname, tmp) # save the data table
}
Of course, for the first loop iteration you need to create an object proj4810_op_iteration_0
before the loop begins, otherwise it won't find anything.
As for the elegance of this approach, I agree more with the list-solution someone else already posted, but if you really want to it this way, this should work.
And please remember for the next time that you ask something, that you provide a minimal reproducible example.
Upvotes: 1
Reputation: 7665
Another approach is to use a list for the dataframes.
Here is a simplified version of your problem solved. It involves calculating the emelents of the fibbonacci sequence. The Desired datatables are
dfList[[1]]
# xnmo xn
# 1 1 2
dfList[[2]]
# xnmo xn
# 1 2 3
dfList[[3]]
# xnmo xn
# 1 3 5
So the first table contains the first and the second part of the sequence. The second table contains the second and the third part of the sequence, etc.
A loop to calculate such tables can be written as follows
dfList = list(data.frame(xnmo=1, xn=1))
for(i in 1:10)
dfList[[i+1]] = data.frame(
xnmo = dfList[[i]]$xn,
xn = dfList[[i]]$xnmo + dfList[[i]]$xn
)
Upvotes: 0