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

为什么R需要数据帧的名称?,r,this,R,This,如果您有这样的数据帧 mydf <- data.frame(firstcol = c(1,2,1), secondcol = c(3,4,5)) 工作但是 mydf[firstcol,] 不会吗?您可以这样做: mydf[,"firstcol"] 请记住,列是第二列,而不是第一列 在您的示例中,要查看mydf[mydf$firstcol,]为您提供了什么,让我们对其进行细分: > mydf$firstcol [1] 1 2 1 所以实际上mydf[mydf$firstcol,

如果您有这样的数据帧

mydf <- data.frame(firstcol = c(1,2,1), secondcol = c(3,4,5))
工作但是

mydf[firstcol,]
不会吗?

您可以这样做:

mydf[,"firstcol"]
请记住,列是第二列,而不是第一列

在您的示例中,要查看
mydf[mydf$firstcol,]
为您提供了什么,让我们对其进行细分:

> mydf$firstcol
[1] 1 2 1
所以实际上
mydf[mydf$firstcol,]

> mydf[c(1,2,1),]
    firstcol secondcol
1          1         3
2          2         4
1.1        1         3
所以您要的是第1行、第2行和第1行。也就是说,您要求第一行与
mydf
的第1行相同,第2行与
mydf
的第2行相同,第3行与
mydf
的第1行相同;您要求两个列

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

> mydf[,firstcol]
Error in `[.data.frame`(mydf, , firstcol) : object 'firstcol' not found
也就是说,当您这样要求列名时,为什么必须在列名周围加引号,而在执行
mydf$firstcol
时却不必加引号呢。答案是,您使用的运算符需要不同类型的参数。您可以查看
“$”
以查看表单x$name,因此第二个参数可以是一个名称,它不带引号。然后,您可以查找
?“[”
,这实际上将引导您进入同一帮助页面。在那里您将找到以下内容,对其进行解释。请注意,“字符”向量需要有带引号的条目(这就是在
R
(和许多其他语言)中输入字符向量的方式)


对于徐旺的解释,没有什么需要补充的。您可能还需要注意的是,该软件包允许您使用一些符号,如
mydf[firstcol==1,]
mydf[,firstcol]
,许多人认为这些符号更自然

> mydf[,firstcol]
Error in `[.data.frame`(mydf, , firstcol) : object 'firstcol' not found
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.