0

Hello I want to apply dplyr arrange function on a column within a for loop, but for some reason it does not work. Here is a minimal example:

for (j in colnames(df1)[3:ncol(df1)]){
  # create datframe for each column
  t <- select(df1, all_of(j))
  t %>% arrange(j)
  var_list[[j]] <- t
  for (i in var_list[[j]]$Timestep )
  
  ### arrange each timestep df by each colun once
  scenario[[i+1]] <- var_list[[j]][min:max,]
  
  # subset data to the scenarios of interest
  }

I guess the Problem is that j delivers a character string "variable", but dplyr arrange requires it without "". I have tried as.name(), paste() and eval parse functions but neither of them worked. Any ideas? Thank you!

R_hub
  • 21
  • 4

2 Answers2

0

This seems to work :

df1 <- mtcars
var_list <- list()
for (j in colnames(df1)[3:ncol(df1)]){
  # create datframe for each column
  t <- select(df1, all_of(j))
  
  var_list[[j]] <- t %>% arrange_at(1)
  for (i in var_list[[j]]$Timestep )
    
    ### arrange each timestep df by each colun once
    scenario[[i+1]] <- var_list[[j]][min:max,]
  
  # subset data to the scenarios of interest
}
var_list
Waldi
  • 39,242
  • 6
  • 30
  • 78
0

Unfortunately does not work. It should sort the column j in ascending order. Maybe arrange is not the best function to use - however order or sort do not work either. Cant get what I am doing wrong. However I found a work around using long data format:

for (j in colnames(df1)[3:ncol(df1)]){
  # create datframe for each timestep
  t <- select(df1, Trial, Timestep, all_of(j))
  var_list[[j]] <- melt(t, id.vars=c("Trial", "Timestep"))
  var_list[[j]] <- var_list[[j]] %>% arrange(value)
R_hub
  • 21
  • 4