R-基礎(chǔ)分享【2】-attach和with

上一次說了數(shù)據(jù)結(jié)構(gòu)中的數(shù)據(jù)框,這一次就說說調(diào)用數(shù)據(jù)框中數(shù)據(jù)的兩個(gè)函數(shù)——attach和with。
選取某個(gè)數(shù)據(jù)框中的某個(gè)特定變量的符號(hào)為:$
有代碼:
summary(mtcars$mpg)
plot(mtcars$mpg,mtcars$disp)
plot(mtcars$mpg,mtcar$wt)
多次輸入mtcars$真的很令人反感,所以這里我們用到了attach( )和with( )。

  • attach( )
    把以上代碼寫成:
    attach(mtcars)
      summary(mpg)
      plot(mpg,disp)
      plot(mpg,wt)
    detach(mtcars)
    其中attach( )函數(shù)是將數(shù)據(jù)框添加到R的搜索路徑中,detach( )是將數(shù)據(jù)框從搜索路徑中移除。
    注:若在綁定數(shù)據(jù)框之前,環(huán)境中已經(jīng)有要提取的某個(gè)特定變量,則會(huì)出現(xiàn)錯(cuò)誤!

    For example:

> 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( )函數(shù)可以避免上述問題。

  • with( )
    重寫上例:
    with(mtcars,{
     summary(mpg,disp,wt)
     plot(mpg,disp)
     plot(mpg,wt)
    })
    注:如果大括號(hào)內(nèi)只有一條語句,那么大括號(hào)可以省略
    函數(shù)with( )有一個(gè)局限性,就是賦值僅僅在括號(hào)內(nèi)生效。
    有代碼:

> 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

**但是你要?jiǎng)?chuàng)建在with( )結(jié)構(gòu)以外的對(duì)象,可以使用<<-替代<-就可實(shí)現(xiàn)!**
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語言實(shí)戰(zhàn)》 R in Action。 作為一個(gè)R語言菜鳥,歡迎大家與我一同學(xué)習(xí)R語言,

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容