Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
964 views
in Technique[技术] by (71.8m points)

r - Filtering single-column data frames

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...