0

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 $.

MLavoie
  • 9,671
  • 41
  • 36
  • 56
NNNN
  • 9
  • 1
  • I don't understand, df$x1 will return the same as df[,1], you must have made a mistake. – user2974951 Sep 21 '18 at 09:42
  • 2
    In f1 - you can't use the `$` to extract a variable like that. You need to use `[[` - so `MyData[[x]]`would work for you. See [this for explanation of extract operators](https://github.com/lgreski/datasciencectacontent/blob/master/markdown/rprog-extractOperator.md) – forestfanjoe Sep 21 '18 at 10:00
  • cannot reproduce your problem. please add the dataset, and proper code – Sal-laS Sep 21 '18 at 10:09
  • 1
    You are more likely to get a meaningful answer if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5965451#5965451). – Paul Rougieux Sep 21 '18 at 10:22

0 Answers0