R语言学习数据科学与R语言数据-R语言-图表-决策-Linux-Python

R-基础分享【2】-attach和with

2016-05-25  本文已影响573人  CharlesSun9

上一次说了数据结构中的数据框,这一次就说说调用数据框中数据的两个函数——attach和with。
选取某个数据框中的某个特定变量的符号为:$
有代码:
summary(mtcars$mpg)
plot(mtcars$mpg,mtcars$disp)
plot(mtcars$mpg,mtcar$wt)
多次输入mtcars$真的很令人反感,所以这里我们用到了attach( )和with( )。

> mpg<-c(25,36,47)
>attach(mtcars)
The following object is masked by .GlobalEnv:

mpg

> plot(mpg,wt)
Error in xy.coords(x, y, xlabel, ylabel, log) :
'x' and 'y' lengths differ
>mpg
[1] 25 36 47

所以,with( )函数可以避免上述问题。

> 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( )结构以外的对象,可以使用<<-替代<-就可实现!**
For example:

>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

本文代码来自于 《R语言实战》 R in Action。 作为一个R语言菜鸟,欢迎大家与我一同学习R语言,

上一篇 下一篇

猜你喜欢

热点阅读