调用数据框中数据时,不想每次都是用 $ ,则可用attach()和with()函数
mtcars是R的一个数据集
mtcars

plot(mtcars$mpg,mtcars$wt)

attach()
attach(mtcars)
plot(mpg,wt) # 此时可直接调用数据框的列名

其中attach()函数是将数据框添加到R的搜索路径中,detach()是将数据框从搜索路径中移除。
注:若在绑定数据框之前,环境中已经有要提取的某个特定变量,则会出现错误!
mpg<-c(25,36,47)
attach(mtcars)
plot(mpg,wt)

with()
上面的例子可写成
with(mtcars,{
plot(mpg,wt)
})
注:如果大括号内只有一条语句,那么大括号可以省略

> with(mtcars,{
stats<-summary(mpg)
stats
})
Min. 1st Qu. Median Mean 3rd Qu. Max.
10.40 15.42 19.20 20.09 22.80 33.90
>stats
Error: object 'stats' not found
要创建在with( )结构以外的对象,可以使用<<-替代<-就可实现!
>with(mtcars,{
nokeepstats<-summary(mpg)
keepstats<<-summary(mpg)
})
> nokeepstats
Error: object 'nokeepstats' not found
> keepstats
Min. 1st Qu. Median Mean 3rd Qu. Max.
10.40 15.42 19.20 20.09 22.80 33.90
网友评论