Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable partial column name matching in an R data.frame? [duplicate]

Tags:

dataframe

r

I would like the following code to error because df$t does not exist. I do not want df$this_is_the_wrong_variable to be returned:

df <- data.frame(
    this_is_the_wrong_variable = c(0, 1),
    r = c(2, 3),
    s = c(4, 5),
    st = c(6, 7), # typo!
)
print(df$t) # this does not give an error!

How is this weird concept called, and how can I disable it?

like image 652
bers Avatar asked Oct 22 '25 03:10

bers


1 Answers

Searching the ?options page for "partial" finds this option:

warnPartialMatchDollar:

logical. If true, warns if partial matching is used for extraction by $.

So setting that option (options(warnPartialMatchDollar = TRUE)) will turn it into a warning.

I don't think there's an easy to to turn only that warning into an error, but looking up a few rows in the ?options help if you set options(warn = 2), all warnings will be treated as errors.

Alternately, you could use tibbles, which don't use partial matching with $ (though it returns NULL will a warning, not an error):

library(tibble)
as_tibble(df)$t
# NULL
# Warning message:
# Unknown or uninitialised column: `t`.
like image 86
Gregor Thomas Avatar answered Oct 24 '25 23:10

Gregor Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!