2018-10-19
閱讀量:
2534
R語言中,attach與detach,及with的區(qū)別
問題描述
R語言中,對數(shù)據(jù)框中的數(shù)據(jù)的進(jìn)行操作時(shí),為了避免重復(fù)地鍵入對象名稱,可使用attach、detach或with。那么attach和with有什么區(qū)別呢?
解答
1、attach()是對what添加路徑索引,避免重復(fù)輸入what名稱。
attach(what, pos = 2L, name = deparse(substitute(what), backtick=FALSE), warn.conflicts = TRUE)
what:數(shù)據(jù)框或列表;
pos=2L:添加的路徑存儲的位置,一般默認(rèn)即可。在對多個(gè)數(shù)據(jù)添加索引時(shí),此位置會變成3L,4L,5L...detach()撤銷索引路徑時(shí),會撤銷對應(yīng)位置的索引儲存,具體例子見后;
name:不懂,遇見需要的情況再補(bǔ)充;
backtick=FALSE:反引號,經(jīng)過測試,該參數(shù)固定為FALSE不可調(diào),再調(diào)用索引時(shí)會用到;
warn.conflicts:是否打印警告。
2、detach()是撤銷attach()建立的路徑索引,常與attach()配合使用。
attach(onedata.frame)
The following objects are masked _by_ .GlobalEnv:
age, name
> age
[1] 20 30 40 50
> name
[1] "Zhangshan" "Lisi" "Wangwu" "Zhaoliu"
> detach(onedata.frame)
> name
錯(cuò)誤: 找不到對象'name'
3、with()函數(shù)
with(data, expr, ...)
表達(dá)式,大括號{}之間的語句都只針對data執(zhí)行,但如果大括號中只有一句的話,則省略大括號。
>with(onedata.frame,{
name
})
[1] Zhangshan Lisi Wangwu Zhaoliu
Levels: Lisi Wangwu Zhangshan Zhaoliu
用with有個(gè)問題就是里面設(shè)置的變量在外部無法訪問:
> with(onedata.frame,{name1<-name})
> name1
錯(cuò)誤: 找不到對象'name1'
解決辦法就是使用<<-賦值符號
> with(onedata.frame,{name1<<-name})
> name1
[1] Zhangshan Lisi Wangwu Zhaoliu
Levels: Lisi Wangwu Zhangshan Zhaoliu






評論(0)


暫無數(shù)據(jù)
CDA考試動態(tài)
CDA報(bào)考指南
推薦帖子
0條評論
0條評論
0條評論
0條評論