I tried using both list.files
and dir
; both commands returned the same output. What is the key difference between these two commands and what's their usage context?
To list all files in a directory in R programming language we use list. files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories.
dir(path) The dir R function returns a character vector of file and/or folder names within a directory. The basic syntax for dir in R is illustrated above.
I know ls is the traditional UNIX method of viewing the files in a directory, and that dir is the windows command prompt equivalent, but both commands work in terminal. If I type in dir , it displays the files and folders in the directory, and if I type ls , it does the same, except with content highlighting.
They are identical in the sense that they take the same arguments, these arguments have identical defaults, and they use the same .Internal
function to execute.
As pointed out by @RichScriven in the comments, a compact and accurate test that they are the same can be run using identical
:
identical(list.files, dir)
[1] TRUE
We can also take a look at their source code.
dir
function (path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE,
recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE,
no.. = FALSE)
.Internal(list.files(path, pattern, all.files, full.names, recursive,
ignore.case, include.dirs, no..))
<bytecode: 0x000000000fe1c388>
<environment: namespace:base>
and
list.files
function (path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE,
recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE,
no.. = FALSE)
.Internal(list.files(path, pattern, all.files, full.names, recursive,
ignore.case, include.dirs, no..))
<bytecode: 0x0000000008811280>
<environment: namespace:base>
Note that
.Internal(list.files(path, pattern, all.files, full.names, recursive,
ignore.case, include.dirs, no..))
is executed in both functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With