PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

[FIXED] How to sort files according to my pattern

 August 29, 2022     csv, r     No comments   

Issue

I'm using fs::dir_ls(path, regexp = paste0("LATO-", "[[:alpha:]]*", ".csv$")) to get a list of files in a specific directory.

The files are, by default, sorted alphabetically. Is there any way in R to keep them sorted according to my pattern

LATO-sty.csv, LATO-lut.csv, LATO-mar.csv, LATO-kwi.csv, LATO-maj.csv, LATO-cze.csv, LATO-lip.csv LATO-sie.csv, LATO-wrz.csv, LATO-paz.csv, LATO-lis.csv, LATO-gru.csv


Solution

The pattern you're describing is not a generic pattern we can apply to all possible values in your file listing. However, we can make sure that if these specific values appear in your vector, they get sorted to the front:

Example fs::dir_ls() data:

files <- c('some/dir/LATO-bar.csv', 'some/dir/LATO-baz.csv', 'some/dir/LATO-foo.csv',
           'some/dir/LATO-kwi.csv', 'some/dir/LATO-lut.csv', 'some/dir/LATO-sty.csv',
           'some/dir/ZLATO-bar.csv', 'some/dir/ZLATO-baz.csv')

Code:

order <- c('LATO-sty.csv', 'LATO-lut.csv', 'LATO-mar.csv', 'LATO-kwi.csv',
           'LATO-maj.csv', 'LATO-cze.csv', 'LATO-lip.csv', 'LATO-sie.csv',
           'LATO-wrz.csv', 'LATO-paz.csv', 'LATO-lis.csv', 'LATO-gru.csv')


# get `files` present in `order`
set1 <- files[fs::path_file(files) %in% order] # extract filenames
ids <- match(fs::path_file(set1), order)       # get matching IDs from `order`
ids_sorted <- sort(ids, index.return=T)        # get sort order
set1_sorted <- set1[ids_sorted$ix]             # apply sort order

# get `files` NOT present in `order`, keep them in the same order
set2 <- files[!fs::path_file(files) %in% order]

# join sets
result <- unname(c(set1_sorted, set2))

Result:

> result
[1] "some/dir/LATO-sty.csv"  "some/dir/LATO-lut.csv"  "some/dir/LATO-kwi.csv"  "some/dir/LATO-bar.csv"  "some/dir/LATO-baz.csv" 
[6] "some/dir/LATO-foo.csv"  "some/dir/ZLATO-bar.csv" "some/dir/ZLATO-baz.csv"


Answered By - Caspar V.
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing