Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
doorisajar opened this issue Jan 10, 2018 · 2 comments
Closed

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

doorisajar opened this issue Jan 10, 2018 · 2 comments
Assignees
Labels

Comments

@doorisajar
Copy link

@doorisajar doorisajar commented Jan 10, 2018

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?

@krlmlr
Copy link
Member

@krlmlr krlmlr commented Jan 17, 2018

Agree that we should throw an error here, but maybe just throw a warning first.

It does create a new column new_col that contains a data frame without column names. Subsequent dplyr operations might fail on that structure.

Look at str(df %>% ...) or dput(df %>% ...) to see the internal structure of the result.

@lock
Copy link

@lock lock bot commented Sep 8, 2018

This old issue has been automatically locked. If you believe you have found a related problem, please file a new issue (with reprex) and link to this issue. https://reprex.tidyverse.org/

@lock lock bot locked and limited conversation to collaborators Sep 8, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants