过滤单列数据帧 [英] Filtering single-column data frames

查看:81
本文介绍了过滤单列数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图过滤只有一列的数据帧。这导致一个向量返回如下:

  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

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

解决方案

使用选择函数的 drop 参数:

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

#col1
#r3 3
#r4 4
#r5 5
/ pre>

的文档中


drop



对于矩阵和数组。如果为TRUE,则结果被强制为最低的
可能维度(请参阅示例)。这仅适用于提取
元素,而不是替换。有关详细信息,请参阅下一步。



I am attempting to filter data frames that have only one column. This results in a vector being returned like so:

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

What I actually want is the data returned like it is for multi-column dataframes:

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

I can see it makes sense to return a vector if there are no other columns, but generally I want see what rows have given that result too. Why does this happen, and is there an easy way to keep the data frame shape in the result, including the rownames?

解决方案

Use the drop argument to the select functions:

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

#   col1
#r3    3
#r4    4
#r5    5

From documentation for [:

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.

这篇关于过滤单列数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆