为什么R需要数据帧的名称?

spe*_*ndo 3 r this

如果你有这样的数据帧

mydf <- data.frame(firstcol = c(1,2,1), secondcol = c(3,4,5))
Run Code Online (Sandbox Code Playgroud)

为什么会

mydf[mydf$firstcol,]
Run Code Online (Sandbox Code Playgroud)

工作但是

mydf[firstcol,]
Run Code Online (Sandbox Code Playgroud)

不会?

Xu *_*ang 10

你可以这样做:

mydf[,"firstcol"]
Run Code Online (Sandbox Code Playgroud)

请记住,该列排在第二位,而不是第一位.

在你的例子中,为了看看是什么mydf[mydf$firstcol,]给你,让我们分解它:

> mydf$firstcol
[1] 1 2 1
Run Code Online (Sandbox Code Playgroud)

所以真的mydf[mydf$firstcol,]是一样的

> mydf[c(1,2,1),]
    firstcol secondcol
1          1         3
2          2         4
1.1        1         3
Run Code Online (Sandbox Code Playgroud)

因此,您要求第1,2和1行.也就是说,您要求第1行与第1 mydf行相同,第2 mydf行与第2行相同,第3行为第3行与第1行相同mydf; 而且你要求两个专栏.

另一个问题是为什么以下不起作用:

> mydf[,firstcol]
Error in `[.data.frame`(mydf, , firstcol) : object 'firstcol' not found
Run Code Online (Sandbox Code Playgroud)

也就是说,为什么当你要求它时,你必须在列名称周围加上引号,而不是当你这样做时mydf$firstcol.答案就是您使用的运算符需要不同类型的参数.您可以查看'$'表单x $ name,因此第二个参数可以是名称,不引用.然后?'[',您可以查找,这实际上会引导您进入相同的帮助页面.在那里你会发现以下内容,它解释了它.请注意,"字符"向量需要引用条目(即您在R(以及许多其他语言)中输入字符向量的方式.

i, j, ...: indices specifying elements to extract or replace.  Indices
      are ‘numeric’ or ‘character’ vectors or empty (missing) or
      ‘NULL’.  Numeric values are coerced to integer as by
      ‘as.integer’ (and hence truncated towards zero).  Character
      vectors will be matched to the ‘names’ of the object (or for
      matrices/arrays, the ‘dimnames’): see ‘Character indices’
      below for further details.
Run Code Online (Sandbox Code Playgroud)