rtidyversecalculated-columns

Mutate/filter column which has same name as another dataframe


I want to do something like this (a silly reprex):

iris %>%
    mutate(mtcars = Sepal.Length * 7) %>%
    filter(mtcars < max(mtcars$mpg))

where the first mtcars refers to a column in iris, while the second mtcars refers to the external data.frame.

I realise I could pre-compute max(mtcars$mpg) or simply relabel the data.frame, but I'm wondering if there is a way to distinguish between the two in situ explicitly? E.g. something like:

iris %>%
    mutate(mtcars = Sepal.Length * 7) %>%
    filter(`mtcars` < max(EXTERNAL::mtcars$mpg))
#              ^                        ^
#            column               Not a column

Solution

  • According to this link - https://rlang.r-lib.org/reference/dot-data.html, the suggested method from the Tidyverse is to use the .data and .env pronouns to distinguish.

    The .data and .env pronouns make it explicit where to find objects when programming with data-masked functions.

    So in this instance the code would be:

    iris %>%
        mutate(mtcars = Sepal.Length * 7) %>%
        filter(mtcars < max(.env$mtcars$mpg))