I was typing MyData$Column1
, MyData$Column2
, etc. too many times, so I wanted to create a function f which made that shorter.
I tried
f1 <- function(x){
return((MyData$x))
}
but f1(Column1) always returned NULL, and so would f1("Column2").
However, when I defined
f2 <- function(y){
return(MyData[,y]
}
This worked, that is, f2(2) returns column 2.
What really mystifies me is that if I run
MyData[,2] == MyData$Column2
then I get the same answer.
I've looked into how different environments are defined in R (i.e., the global environment is different from the environment inside a specific function, and you'd need to use the <<- if you wanted to write over a global variable inside a function environment, etc.).
But that doesn't seem to be related to this problem: If I can access MyData in one case, I should also be able to do so in the other.
I've also generally searched Google and StackOverflow, and looked over the documentation for $.