在使用数字矩阵索引数据框时,为什么类会从整数更改为字符?

N8T*_*TRO 5 r

如果我用矩阵索引所有整数的data.frame,我得到预期的结果.

df <- data.frame(c1=1:4, c2=5:8)
df1
#  c1 c2
#1  1  5
#2  2  6
#3  3  7
#4  4  8

df1[matrix(c(1:4,1,2,1,2), nrow=4)]
# [1] 1 6 3 8
Run Code Online (Sandbox Code Playgroud)

如果data.frame有一列字符,则结果是所有字符,即使我只是对整数列建立索引.

df2 <- data.frame(c0=letters[1:4], c1=1:4, c2=5:8)
df2
#  c0 c1 c2
#1  a  1  5
#2  b  2  6
#3  c  3  7
#4  d  4  8

df2[matrix(c(1:4,2,3,2,3), nrow=4)]
# [1] "1" "6" "3" "8"

class(df[matrix(c(1:4,2,3,2,3), nrow=4)])
# [1] "character"

df2[1,2]
# [1] 1
Run Code Online (Sandbox Code Playgroud)

我最好的猜测是,R太忙了,无法通过答案来检查它们是否都来自某个班级.任何人都可以解释为什么会这样吗?

Hen*_*rik 4

其中?Extract描述了通过数字矩阵进行索引适用于矩阵和数组。因此,这种索引首先适用于数据框可能会令人惊讶。

[.data.frame然而,如果我们查看( )的代码,我们会发现当使用 a ingetAnywhere(`[.data.frame`)从 a 中提取元素时, the首先被强制转换为 a with :data.framematrixidata.framematrixas.matrix

function (x, i, j, drop = if (missing(i)) TRUE else length(cols) == 
            1) 
{
# snip
  if (Narg < 3L) {
# snip
    if (is.matrix(i)) 
      return(as.matrix(x)[i])
Run Code Online (Sandbox Code Playgroud)

然后看?as.matrix

“如果只有原子列和任何非(数字/逻辑/复杂)列,数据帧的方法将返回字符矩阵”。

因此,由于“df2”中的第一列属于 类character,因此将在提取发生之前as.matrix将整个数据帧强制转换为矩阵。character