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.
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:
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
Another stackoverflow reference: http://stackoverflow.com/questions/21598295/how-to-debug-invalid-subscript-type-integer-error-in-r
I just got bit by this issue as well.
Duplicate of #1400
Most helpful comment
Interesting. Also, the thread suggests a good workaround by quoting the field name: