Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data.frames in R: name autocompletion?

Tags:

dataframe

r

Sorry if this is trivial. I am seeing the following behaviour in R:

> myDF <- data.frame(Score=5, scoreScaled=1)
> myDF$score ## forgot that the Score variable was capitalized
[1] 1

Expected result: returns NULL (even better: throws error).

I have searched for this, but was unable to find any discussion of this behaviour. Is anyone able to provide any references on this, the rationale on why this is done and if there is any way to prevent this? In general I would love a version of R that is a little stricter with its variables, but it seems that will never happen...

like image 540
Rob Hall Avatar asked Sep 29 '15 22:09

Rob Hall


1 Answers

The $ operator needs only the first unique part of a data frame name to index it. So for example:

> d <- data.frame(score=1, scotch=2)
> d$sco
NULL
> d$scor
[1] 1

A way of avoiding this behavior is to use the [[]] operator, which will behave like so:

> d <- data.frame(score=1, scotch=2)
> d[['scor']]
NULL
> d[['score']]
[1] 1

I hope that was helpful.

Cheers!

like image 137
mescarra Avatar answered Sep 22 '22 14:09

mescarra