调用数据框中数据的两个函数——attach和with

调用数据框中数据时,不想每次都是用 $ ,则可用attach()和with()函数
mtcars是R的一个数据集
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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容