Skip to content

What's going on when mutate RHS is a data frame? #3298

@doorisajar

Description

@doorisajar

Recently I came across a use case where a colleague wanted to duplicate a column via mutate, but refer to the target column programmatically. In the course of doing this, I checked to see what would happen if I used [ rather than [[, and found that not only did mutate not fail, but I got a strange result:

library(dplyr)

my_col <- "base_col"

df <- data.frame("a" = c(1, 2),
                 "b" = c(2, 3),
                 "base_col" = c(3, 4))

# this works fine
df %>% mutate(new_col = .[[my_col]])
#>   a b base_col new_col
#> 1 1 2        3       3
#> 2 2 3        4       4

# what's going on here?
df %>% mutate(new_col = .[my_col])
#>   a b base_col new_col. new_col.
#> 1 1 2        3        3        3
#> 2 2 3        4        4        4

mutate is receiving a data.frame here:

> df[my_col]
  base_col
1        3
2        4

...but it isn't obvious why the column gets added twice or where the periods are coming from.

I think the right behaviour here is probably to fail, unless I'm missing something?

Metadata

Metadata

Labels

bugan unexpected problem or unintended behavior

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions