Dplyr: Somewhat unexpected "invalid subscript type 'double'" when using $

Created on 26 Nov 2015  路  5Comments  路  Source: tidyverse/dplyr

Dear all,

I wanted to add a new column to a data frame with a constant value from a list:

someVariable <- list(a = 3, b = 5)
dplyr::mutate(mtcars, newColumn = someVariable$a) %>% head

This works.

But if a variable of the same name ("a") is present, I get an error:

someVariable <- list(a = 3, b = 5)
a <- 10
dplyr::mutate(mtcars, newColumn = someVariable$a) %>% head
Error: invalid subscript type 'double'

A fix consists in encapsulating the offending call with I():

someVariable <- list(a = 3, b = 5)
a <- 10
dplyr::mutate(mtcars, newColumn = I(someVariable$a)) %>% head()

(edit: this fix might not be advisable as newColumn is of class AsIs and not of the expected double. To avoid the issue, simply store the value into a new variable and use this new variable instead of someVariable$a in the call to dplyr::mutate.)

This is reminiscent of bug #421 , which is closed.

Whether it's something to fix or not, I leave it up to you but it was a bit maddening to debug (in my case, the variable 'a' was only sometimes present in the global environment, so my tests were passing when run from a separate environment, but not always when run from the console.).

thanks.

Most helpful comment

Interesting. Also, the thread suggests a good workaround by quoting the field name:

someVariable <- list(a = 3, b = 5)
a <- 10
dplyr::mutate(mtcars, newColumn = someVariable$'a') %>% head

All 5 comments

I've been having this same issue also, and I agree that the problem is hard to debug at first, before you realize what's going on. Here's a stack overflow post I made before seeing this bug report:

http://stackoverflow.com/questions/34054968/mutate-is-trying-to-extract-using-the-value-of-a-global-variable-when-using-th

I've also had this issue at least once in the past when I was trying to extract a function from an object, and the function happened to have the same name as a different function on the search path (while doing this inside a mutate).

Interesting. Also, the thread suggests a good workaround by quoting the field name:

someVariable <- list(a = 3, b = 5)
a <- 10
dplyr::mutate(mtcars, newColumn = someVariable$'a') %>% head

I just got bit by this issue as well.

Duplicate of #1400

Was this page helpful?
0 / 5 - 0 ratings