在R中,df [“x”]和df $ x之间有什么区别? [英] In R, What is the difference between df["x"] and df$x

查看:3678
本文介绍了在R中,df [“x”]和df $ x之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在哪里可以找到有关通过以下方式调用数据框架中的列之间的差异的信息:

Where can I find information on the differences between calling on a column within a data.frame via:

df <- data.frame(x=1:20,y=letters[1:20],z=20:1)

df$x
df["x"]

他们都返回相同的结果,但不一定是相同的格式。我注意到的另一件事是,df $ x返回一个列表。而df [x]返回一个data.frame。

They both return the "same" results, but not necessarily in the same format. Another thing that I've noticed is that df$x returns a list. Whereas df["x"] returns a data.frame.

编辑:但是,知道在哪种情况下使用哪一种已经成为一个挑战。这里有最好的做法,还是真的来了解知道命令或功能需要什么?到目前为止,如果我的功能首先不起作用(试错),我刚刚骑自行车。

However, knowing which one to use in which situation has become a challenge. Is there a best practice here or does it really come down to knowing what the command or function requires? So far I've just been cycling through them if my function doesn't work at first (trial and error).

推荐答案

如果我没有误会, df $ x df [['x']] 相同。 [[]用于选择任何单个元素,而 [返回所选元素的列表。另见语言参考 。我通常看到[[用于列表,数组和$用于获取单个列或元素。如果您需要一个表达式(例如df [[name]]或df [,name]),则使用[或[[符号])。如果选择了多个列,也会使用[符号]。例如df [,c('name1','name2')]。我不认为这是最好的做法。

If I'm not mistaken, df$x is the same as df[['x']]. [[ is used to select any single element, whereas [ returns a list of the selected elements. See also the language reference. I usually see that [[ is used for lists, [ for arrays and $ for getting a single column or element. If you need an expression (for example df[[name]] or df[,name]), then use the [ or [[ notation also. The [ notation is also used if multiple columns are selected. For example df[,c('name1', 'name2')]. I don't think there is a best-practices for this.

这篇关于在R中,df [“x”]和df $ x之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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