繁体   English   中英

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

[英]Unexpected behaviour: Removing rows from data frame converts to vector R

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

一个例子:

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 时,丢失 colname 是一件麻烦事,我完全丢失了名称:

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

这是预期的吗? 如果是这样,为什么,以及如何从简单的 dataframe 中删除行而不丢失列名?

我们可以默认使用drop作为?Extract

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

并且drop文档说

drop - 对于矩阵和 arrays。 如果为 TRUE,则将结果强制转换为可能的最低维度(参见示例)。 这仅适用于提取元素,不适用于替换。 有关详细信息,请参阅下降。

drop是 TRUE 尤其是data.frame 但是,在subsetdata.tabletibble中情况并非如此

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

有单列或单行的情况


使用tibble ,它不会降低尺寸

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),]

或与data.table

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM