gpt4 book ai didi

r - 意外行为 : Removing rows from data frame converts to vector R

转载 作者:行者123 更新时间:2023-12-04 10:15:00 25 4
gpt4 key购买 nike

我在 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 时,丢失 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

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

最佳答案

我们可以使用 drop默认情况下 ?Extract

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



drop文件说

drop - For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.


drop是真的,尤其是 data.frame .但是, subset 的情况并非如此。或与 data.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)]

关于r - 意外行为 : Removing rows from data frame converts to vector R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61109398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com