Skip to content

should mutate_at lambdas be able to refer to other columns in .data? #4183

@MilesMcBain

Description

@MilesMcBain

As a simple example, let's say you have a normalising constant in one dataframe column and you need to normalise many other columns. mutate_at seems like it would be convenient to do this, but you can't refer to other columns in the dataframe apart from . cleanly.

Example:

library(tidyverse)

## Works but hardcoding dataset name feels lame.
iris %>%
  mutate_at(vars(starts_with("Sepal")),
            ~ . / iris$Petal.Width) %>%
  head()
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1         25.5       17.50          1.4         0.2  setosa
#> 2         24.5       15.00          1.4         0.2  setosa
#> 3         23.5       16.00          1.3         0.2  setosa
#> 4         23.0       15.50          1.5         0.2  setosa
#> 5         25.0       18.00          1.4         0.2  setosa
#> 6         13.5        9.75          1.7         0.4  setosa

## Fails
iris %>%
  mutate_at(vars(starts_with("Sepal")),
            ~ . / Petal.Width) %>%
  head()
#> Error in mutate_impl(.data, dots): Evaluation error: object 'Petal.Width' not found.

## Fails differently
iris %>%
  mutate_at(vars(starts_with("Sepal")),
            ~ . / .data$Petal.Width) %>%
  head()
#> Error in mutate_impl(.data, dots): Column `Sepal.Length` must be length 150 (the number of rows) or one, not 0

Created on 2019-02-15 by the reprex package (v0.2.1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions