James Wang
James Wang

Reputation: 1311

Why doesn't df$"columnname" work in a function?

Why can't I retrieve a column using df$"columnname" from within a function, when it works perfectly fine outside of one?

With a dataframe:

> df <- as.data.frame(cbind(col1=c(0,1), col2=c(2,3)))
> df
     col1 col2
[1,]    0    2
[2,]    1    3

df$"col1" works fine normally. However, this returns NULL when I put it in a function.

> df_fn <- function(name) { df$name }
> df_fn("col1")
NULL

However, it works perfectly fine when I use the [[]] form:

> df_fn2 <- function(name) { df[[name]] }
> df_fn2("col1")
[1] 0 1

Looked around and didn't see any answers to this (though it was hard trying to search a symbol like $). Practically speaking, I can use the [[]] form just fine, but I'm curious as to what in R's internals causes this.

Upvotes: 1

Views: 278

Answers (1)

James Wang
James Wang

Reputation: 1311

Looking at the ?"$" docs as per jeremycg's comment:

x$name is equivalent to x[["name", exact = FALSE]]

When just typing in df$"col1" it works. When typing in df_fn("name") it doesn't work because, as per the docs, it's literally trying to look up "name" as a column. The proof here:

> df <- as.data.frame(cbind(col1=c(0,1), col2=c(2,3), name=c(4,5)))
> df_fn("name")
[1] 4 5

Upvotes: 3

Related Questions