意外的行为:从数据框中删除行将转换为向量R

我看到了R中看起来很奇怪的行为:当我从一个简单的数据框中删除行时,该对象被转换为向量。这是预期的吗?

一个例子:

a = data.frame(x = 1:10) #create simple dataframe
> a
    x
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

> class(a) #check its a dataframe
[1] "data.frame"

a <- a[-(1:2), ] #remove the first two rows from the dataframe

> a #check the rows are gone (but note result prints as a vector)
[1]  3  4  5  6  7  8  9 10

> class(a) #check the class to see that it is actually a vector
[1] "integer"

as.data.frame(a) #convert back to dataframe, and find that the name of the col is changed. 
   a
1  3
2  4
3  5
4  6
5  7
6  8
7  9
8 10

当我申请dplyr时,失去姓氏是一件麻烦事,在这里我完全失去了名字:

data.frame(x = 1:10) %>%
  .[-(1:2), ] %>%
  as.data.frame()
   .
1  3
2  4
3  5
4  6
5  7
6  8
7  9
8 10

我期望:

   x
1  3
2  4
3  5
4  6
5  7
6  8
7  9
8 10

这是预期的吗?如果是这样,为什么?如何在不丢失名称的情况下从简单数据框中删除行?

评论
  • 杨柳清风
    杨柳清风 回复

    We can use the drop as by default for ?Extract

    x [i,j,...,drop = TRUE]

    and the drop documentation says

    drop-用于矩阵和数组。如果为TRUE,则将结果强制为最小尺寸(请参见示例)。这仅适用于提取元素,不适用于替换。有关更多详细信息,请参见drop。

    drop is TRUE especially with data.frame. But, that is not the case in subset or with data.table or tibble

    a[-(1:2),, drop = FALSE] 
    #    x
    #3   3
    #4   4
    #5   5
    #6   6
    #7   7
    #8   8
    #9   9
    #10 10
    

    这是单列或单行的情况

    With tibble, it wouldn't drop the dimensions

    library(dplyr)
    tibble(x = 1:10) %>% 
       slice(-(1:2))
    # A tibble: 8 x 1
    #      x
    #  <int>
    #1     3
    #2     4
    #3     5
    #4     6
    #5     7
    #6     8
    #7     9
    #8    10
    

    要么

    tibble(x = 1:10)[-(1:2),]
    

    Or with data.table

    library(data.table)
    data.table(x = 1:10)[-(1:2)]