[R] Extracting a data frame element using a missing argument as index results in no error
William Barcelona
w||||@m@|@b@rce|on@ @end|ng |rom |rb@gov
Fri Aug 15 19:31:14 CEST 2025
NONCONFIDENTIAL // EXTERNAL
The following function foo indexes the mtcars data frame by x, and I supply no default value to the argument x. When I call the function without any argument values, I surprisingly get no error and the entire mtcars data frame is returned. It seems that x is being treated as an empty index and thus mtcars[x] is being treated as mtcars[]. But is using x as the index for `[` not enough to get the promise to be resolved and hit the expected 'argument is missing' error? If I use x by itself beforehand in foo2 below, I get the expected error.
foo <- function(x) mtcars[x]
foo()
# mtcars is printed in full
foo2 <- function(x) {x; mtcars[x]}
foo2()
Error in foo2() : argument "x" is missing, with no default
Session info:
R version 4.4.1 (2024-06-14)
Platform: x86_64-ubuntu18-linux-gnu
Running under: Ubuntu 18.04.6 LTS
Matrix products: default
BLAS/LAPACK: /apps/intel/2019.1/compilers_and_libraries_2019.1.144/linux/mkl/lib/intel64_lin/libmkl_gf_lp64.so; LAPACK version 3.7.0
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
time zone: America/New_York
tzcode source: system (glibc)
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] MKLthreads_0.1
loaded via a namespace (and not attached):
[1] compiler_4.4.1
William Barcelona
Data & Technology Analyst
Global Financial Institutions | Division of International Finance
Federal Reserve Board
william.l.barcelona using frb.gov<mailto:william.l.barcelona using frb.gov>
[[alternative HTML version deleted]]
More information about the R-help
mailing list