我看到了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
and the
drop
documentation saysdrop
is TRUE especially withdata.frame
. But, that is not the case insubset
or withdata.table
ortibble
这是单列或单行的情况
With
tibble
, it wouldn't drop the dimensions要么
Or with
data.table