不使用的另一个原因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