gpt4 book ai didi

r - 过滤单列数据框

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

我正在尝试过滤只有一列的数据框。这会导致返回一个向量,如下所示:

single.c <- data.frame(col1=c(1,2,3,4,5), row.names=C("r1","r2","r3","r4","r5"))
single.c[single.c$col1 > 2,]

[1] 3 4 5

我真正想要的是像多列数据帧一样返回的数据:
multi.c <- data.frame(col1=c(1,2,3,4,5), col2=c(1,2,3,4,5), row.names=c("r1","r2","r3","r4","r5"))
multi.c[multi.c$col2 > 2,]

col1 col2
r3 3 3
r4 4 4
r5 5 5

如果没有其他列,我可以看到返回向量是有意义的,但通常我想看看哪些行也给出了该结果。为什么会发生这种情况,是否有一种简单的方法可以在结果中保留数据框形状,包括行名?

最佳答案

使用 drop选择函数的参数:

single.c[single.c$col1 > 2, ,drop=F]

# col1
#r3 3
#r4 4
#r5 5

来自 [ 的文档:

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.

关于r - 过滤单列数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12090896/

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