admin 发表于 2014-9-7 11:01:45

R中attach和detach函数?

R之所以功能强大,因为R具有非常丰富的能够完成许多事情的函数。面对如此多的函数,若是逐一地学习,一来时间不允许,二来也没有必要。我们只需要根据我们的问题域,来学习和使用相应的R函数。而这些R函数,有些就是基本包(即R软件安装后就存在的包)里面的函数,有些则是扩展包(需要我们另外安装的包,如何安装,查阅install.packages()函数)里面的函数。    如何学习R中函数呢?我的建议是通过R的帮助文档和函数实例一起来学习。现在,我以attach和detach函数为例,来说说如何学习和掌握这两个函数。第一步:查阅R函数帮助文档>?attach
或者>help(attach)
通过上面命令成功打开attach函数帮助文档后,你会看到关于该函数标题、描述、用法、参数、详情、值、实践、参考、拓展和实例,阅读这一份文档就能够让我们又好又快地掌握并应用该函数。通过attach函数就可以把数据集添加到R搜索路径里面。这意味着当评估一个变量时数据集能够被R搜索到,因此这个数据集的对象能够通过它们简单的名字就可以获得。通过dettach函数就可以把已经添加到R搜索路径里面的数据集移除。因此attach和detach函数,总是配对使用。【提示:使用attach函数添加某个数据集后,针对该数据集完成相应操作后,请移除该数据集,以提高内存资源的利用率】第二步:查阅R函数实例> example(attach)

attach> require(utils)

attach> summary(women$height)   # refers to variable 'height' in the data frame
   Min. 1st Qu.Median    Mean 3rd Qu.    Max.
   58.0    61.5    65.0    65.0    68.5    72.0

attach> attach(women)

attach> summary(height)         # The same variable now available by name
   Min. 1st Qu.Median    Mean 3rd Qu.    Max.
   58.0    61.5    65.0    65.0    68.5    72.0

attach> height <- height*2.54   # Don't do this. It creates a new variable

attach>                         # in the user's workspace
attach> find("height")
".GlobalEnv" "women"   

attach> summary(height)         # The new variable in the workspace
   Min. 1st Qu.Median    Mean 3rd Qu.    Max.
147.3   156.2   165.1   165.1   174.0   182.9

attach> rm(height)

attach> summary(height)         # The original variable.
   Min. 1st Qu.Median    Mean 3rd Qu.    Max.
   58.0    61.5    65.0    65.0    68.5    72.0

attach> height <<- height*25.4# Change the copy in the attached environment

attach> find("height")
"women"

attach> summary(height)         # The changed copy
   Min. 1st Qu.Median    Mean 3rd Qu.    Max.
   1473    1562    1651    1651    1740    1829

attach> detach("women")

【温馨话语】当我们真正地热爱这个世界时,我们才真正地活在这个世界上。我是记事本,微信号:data985(私人号),data985_com(公众号),,你们在R路上的朋友,一起欣赏R路上的风景。赠人玫瑰,手有余香。若是觉得此文有用,欢迎分享给更多的人,让更多的人受用。你若安好,便是晴天。若是朋友们有什么想法或建议,欢迎给我留言或者私信于我。



页: [1]
查看完整版本: R中attach和detach函数?