你使用attach()还是通过名称或切片调用变量? [英] Do you use attach() or call variables by name or slicing?

查看:163
本文介绍了你使用attach()还是通过名称或切片调用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多介绍R书籍和指南开始附加一个 data.frame 的做法,以便您可以按名称调用变量。我总是发现有利于调用变量 $ 记法或方括号切片 [,2] 。这样我可以使用多个 data.frame ,而不会混淆它们和/或使用迭代来连续调用感兴趣的列。我注意到Google最近发布了 R 的编码指南包含此行

Many intro R books and guides start off with the practice of attaching a data.frame so that you can call the variables by name. I have always found it favorable to call variables with $ notation or square bracket slicing [,2]. That way I can use multiple data.frames without confusing them and/or use iteration to successively call columns of interest. I noticed Google recently posted coding guidelines for R which included the line


1)附加:避免使用

1) attach: avoid using it

人们对这种做法有什么感觉?

How do people feel about this practice?

推荐答案

与您的朋友

I never use attach. with and within are your friends.

示例代码 :

> N <- 3
> df <- data.frame(x1=rnorm(N),x2=runif(N))
> df$y <- with(df,{
   x1+x2
 })
> df
          x1         x2          y
1 -0.8943125 0.24298534 -0.6513271
2 -0.9384312 0.01460008 -0.9238312
3 -0.7159518 0.34618060 -0.3697712
> 
> df <- within(df,{
   x1.sq <- x1^2
   x2.sq <- x2^2
   y <- x1.sq+x2.sq
   x1 <- x2 <- NULL
 })
> df
          y        x2.sq     x1.sq
1 0.8588367 0.0590418774 0.7997948
2 0.8808663 0.0002131623 0.8806532
3 0.6324280 0.1198410071 0.5125870

编辑:hadley提到在注释中转换。这里是一些代码:

hadley mentions transform in the comments. here is some code:

 > transform(df, xtot=x1.sq+x2.sq, y=NULL)
       x2.sq       x1.sq       xtot
1 0.41557079 0.021393571 0.43696436
2 0.57716487 0.266325959 0.84349083
3 0.04935442 0.004226069 0.05358049

这篇关于你使用attach()还是通过名称或切片调用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆