不使用的另一個原因attach
:它允許僅訪問數據幀的列的值以訪問(訪問),並且與連接時相同。它不是該列當前值的簡寫。舉兩個例子:
> head(cars)
speed dist
1 4 2
2 4 10
3 7 4
4 7 22
5 8 16
6 9 10
> attach(cars)
> # convert stopping distance to meters
> dist <- 0.3048 * dist
> # convert speed to meters per second
> speed <- 0.44707 * speed
> # compute a meaningless time
> time <- dist/speed
> # check our work
> head(cars)
speed dist
1 4 2
2 4 10
3 7 4
4 7 22
5 8 16
6 9 10
未發生任何變化的cars
數據,即使dist
和speed
被分配到集製作。
如果明確指定回數據集...
> head(cars)
speed dist
1 4 2
2 4 10
3 7 4
4 7 22
5 8 16
6 9 10
> attach(cars)
> # convert stopping distance to meters
> cars$dist <- 0.3048 * dist
> # convert speed to meters per second
> cars$speed <- 0.44707 * speed
> # compute a meaningless time
> cars$time <- dist/speed
> # compute meaningless time being explicit about using values in cars
> cars$time2 <- cars$dist/cars$speed
> # check our work
> head(cars)
speed dist time time2
1 1.78828 0.6096 0.5000000 0.3408862
2 1.78828 3.0480 2.5000000 1.7044311
3 3.12949 1.2192 0.5714286 0.3895842
4 3.12949 6.7056 3.1428571 2.1427133
5 3.57656 4.8768 2.0000000 1.3635449
6 4.02363 3.0480 1.1111111 0.7575249
的dist
和speed
了在計算time
引用是原始(未轉化的)值;當連接cars
時,cars$dist
和cars$speed
的值。
一個問題是,你可能在內存中有其他對象,稱爲(在你的例子中)「工作」或「收入」。如果你想使用它們,但是使用'attach()'數據框'x',很容易混淆使用'x $ job'和'job',或者'x $ income'和'income'對象。 – 2012-04-08 04:20:36