Slavka Slavka - 1 month ago 8
R Question

Problems with attach() in R

i have a list in R, which i attached.

> attach(myList)
> summary(myList)
Length Class Mode
grData 3 data.frame list
maxDate 1 POSIXct numeric
query 1 -none- character
newData 3 data.frame list
updateQuery 1 -none- function


Okay, my list is really attached

> search()
[1] ".GlobalEnv" "myList" "package:xlsx" "package:xlsxjars"
[5] "package:rJava" "package:quantmod" "package:TTR" "package:xts"
[9] "package:zoo" "package:tidyr" "package:stringr" "package:RPostgreSQL"
[13] "package:DBI" "package:dplyr" "tools:rstudio" "package:stats"
[17] "package:graphics" "package:grDevices" "package:utils" "package:datasets"
[21] "package:methods" "Autoloads" "package:base"


grData data frame from my list has 11 rows:

> summary(myList$grData)
date application_id value
Min. :2016-10-01 Min. : 7.0 Min. : 5769
1st Qu.:2016-10-01 1st Qu.: 9.5 1st Qu.: 33113
Median :2016-10-01 Median :12.0 Median : 65821
Mean :2016-10-01 Mean :22.0 Mean :106336
3rd Qu.:2016-10-01 3rd Qu.:37.5 3rd Qu.:108861
Max. :2016-10-01 Max. :49.0 Max. :507376


But when i try to call grData without myList, i get data frame with 0 rows

> summary(grData)
date application_id value
Min. :NA Min. : NA Min. : NA
1st Qu.:NA 1st Qu.: NA 1st Qu.: NA
Median :NA Median : NA Median : NA
Mean :NA Mean :NaN Mean :NaN
3rd Qu.:NA 3rd Qu.: NA 3rd Qu.: NA
Max. :NA Max. : NA Max. : NA


UPD. There is no grData object in globalEnv

> ls()
[1] "checkDbLag" "con" "i" "newDate" "myList" "updateQuery"
[7] "x"


Where could be problem?

Answer

The use of attach() is actually not recommended by many R style guides (like http://google-styleguide.googlecode.com/svn/trunk/google-r-style.html#attach) because it can lead to wrong results.

As suggested by https://www.r-bloggers.com/to-attach-or-not-attach-that-is-the-question/ you have three better options:

  1. Reference variables directly (e.g. lm(ds$x ~ ds$y))
  2. Specify the dataframe for commands which support this (e.g. lm(y ~ x, data=ds))
  3. Use the with() function, which returns the value of whatever expression is evaluated (e.g. with(ds,lm(y ~x))) (Also note the within() function, which is similar to with(), but returns a modified object.)

If you still want to use attach() even given all the alternatives, I suggest you provide a fully reproducible example. By reading your code it seems that you are providing an incomplete output (one time you reference your list as myList, other you reference it as RollingMau).

Comments