SiH
SiH

Reputation: 1546

Related to loop in R

I have a some files in a folder and I could list them using dir()

epochs <- dir(path = paste0(getwd(), "/", "model"))
epochs
  [1] "epoch 0"  "epoch 1"  "epoch 10" "epoch 11" "epoch 12" "epoch 13" "epoch 14" "epoch 15" "epoch 16" "epoch 17" "epoch 18"
 [12] "epoch 19" "epoch 2"  "epoch 20" "epoch 21" "epoch 22" "epoch 23" "epoch 24" "epoch 25" "epoch 26" "epoch 27" "epoch 28"
 [23] "epoch 29" "epoch 3"  "epoch 30" "epoch 31" "epoch 32" "epoch 33" "epoch 34" "epoch 35" "epoch 36" "epoch 37" "epoch 38"
 [34] "epoch 39" "epoch 4"  "epoch 40" "epoch 41" "epoch 42" "epoch 43" "epoch 44" "epoch 45" "epoch 46" "epoch 47" "epoch 48"
 [45] "epoch 49" "epoch 5"  "epoch 50"

When i try to loop though these files -

for (epoch in epochs)
{
  print(epoch)
}

The output is as follows -

[1] "epoch 0"
[1] "epoch 1"
[1] "epoch 10"
[1] "epoch 11"
[1] "epoch 12"
[1] "epoch 13"
[1] "epoch 14"
[1] "epoch 15"
[1] "epoch 16"
[1] "epoch 17"
[1] "epoch 18"
[1] "epoch 19"
[1] "epoch 2"
[1] "epoch 20"
[1] "epoch 21"
[1] "epoch 22"
[1] "epoch 23"
[1] "epoch 24"
[1] "epoch 25"
[1] "epoch 26"
[1] "epoch 27"
[1] "epoch 28"
[1] "epoch 29"
[1] "epoch 3"
[1] "epoch 30"
...

I want to loop in increasing order but the sequence is different. How can I correct it?

Upvotes: 2

Views: 26

Answers (1)

akrun
akrun

Reputation: 887068

If we need to sort them before looping

library(gtools)
epochs1 <- mixedsort(epochs)

and then do the loop

Upvotes: 2

Related Questions