Q:

rev() in r and how to apply it to a list using loops

I have a list of say {a,b,c,d,...} and each element, a,b,c,d, ...  are data.table that I need to reverse the order of, however, for the data.table I only want to rev() all of it except the first column, as it is an ID.  I tried using loops to do it but it returned
Error in `[<-.data.table`(`*tmp*`, , -1, value = list(code_a = c("a",  : 
  Item 1 of column numbers in j is -1 which is outside range [1,ncol=4].  Use column names instead in j to add new columns. 

Example:
a <- c("a","b","c","d","e","f")
b <- 1:6
c <- c("F","E","D","C","B","A")
d <- 10:15
dt1 <- data.table("ID" = b, "code_a" = a)
dt2 <- data.table("ID" = b, "code_c" = c)
dt3 <- data.table("ID" = b, "code_d" = d)
dt <- list(dt1,dt2,dt3)
rev_dt <- rev(dt)
merged_list <- list()
rev_merged_list <- list()
rev_merged_list <- Reduce(merge, rev_dt, accumulate = TRUE)
merged_list <- rev_merged_list
merged_list <- rev(merged_list)

for(z in 1:length(dt)){
  merged_list[[z]][,-1] = rev(merged_list[[z]][,-1])
}

More Information:
The for loop here is supposed to be:
- for z from 1 to the length of dt
- the merged_list element z (which with double square brackets) should be a data.table
- where the data does not include the first column
- should be assigned to the rev of the same element z, where the first column is also excluded
Does this logic hold for the above loop?  I am unsure what is wrong! 
Expected Output:
output_ <- list()
a_ <- data.table("ID" = b, "code_a" = a, "code_c" = c, "code_d" = d)
b_ <- data.table("ID" = b, "code_c" = c, "code_d" = d)
c_ <- data.table("ID" = b, "code_d" = d)
output_[[1]] <- a_
output_[[2]] <- b_
output_[[3]] <- c_
output_

I was told yesterday that the merge above i can specify a right hand merge, however in doing so, I need to specify a by = "ID" in the merge, but I am unsure what is the x and y values in the case of merging multiple sets of data. 
I am also under the impression that lapply() can do the same thing instead of loop, but I am unsure in this case how might I achieved that.  Thanks~

A:

We can use setcolorder 
for(i in seq_along(merged_list)){
   setcolorder(merged_list[[i]],
         c(names(merged_list[[i]])[1], rev(names(merged_list[[i]])[-1])))
   }

all.equal(merged_list, output_, check.attributes = FALSE)
#[1] TRUE

