aiatay7n
aiatay7n

Reputation: 182

Dataframe rownames boolean solution?

Rownames of a dataframe disappear upon sub-setting:

a <- LETTERS[1:10]
b <- rnorm(10)
dfa <- data.frame(b)
rownames(dfa) <- a
dfa
dfa2 <- dfa[1:8,]; dfa2

> dfa
            b
A -1.16592168
B -2.34631741
C -0.31412021
D -0.21755236
E -1.53238321
F -1.32780061
G  0.36072942
H -0.01840526
I -0.66500107
J -1.16027936
> dfa2 <- dfa[1:8,]; dfa2
[1] -1.16592168 -2.34631741 -0.31412021 -0.21755236 -1.53238321 -1.32780061  0.36072942 -0.01840526
Is there a Boolean solution? plyr /dplyr solutions exist. 

How can we do this in the first step without having to add row names back to dfa2? Observation - this problem does not appear to exist if dfa has 2 or more variables.

I have looked at a number of similar posts but they do not address this specifically enough.

Upvotes: 2

Views: 46

Answers (2)

akrun
akrun

Reputation: 887098

We can use convert to data.table without using the drop

library(dat.table)
setDT(dfa)[1:8]

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

When we have only one column in the dataframe the result is coerced to the lowest possible dimension i.e a vector here. (see ?Extract). To avoid that use drop = FALSE while subsetting.

df2 <- dfa[1:8, ,drop = FALSE]
df2
#           b
#A  0.04729636
#B  0.59639094
#C -0.29766849
#D -2.51843915
#E -0.75433974
#F  0.20539938
#G  1.05879253
#H  0.31234443

Upvotes: 2

Related Questions