John Mount explains why you might want to add drop = FALSE
to your data.frame operations:
We were merely trying to re-order the rows and the result was converted to a vector. This happened because the rules for
[ , ]
change if there is only one result column. This happens even if the there had been only one input column. Another example is:d[,]
is also vector in this case.The issue is: if we are writing re-usable code we are often programming before we know complete contents of a variable or argument. For a
data.frame
named “g
” supplied as an argument:g[vec, ]
can be adata.frame
or avector
(or even possibly alist
). However we do know ifg
is adata.frame
theng[vec, , drop = FALSE]
is also adata.frame
(assumingvec
is a vector of valid row indices or alogical
vector, note:NA
induces some special cases).We care as
vector
s anddata.frame
s have different semantics, so are not fully substitutable in later code.
Definitely read the comments on this one as well, as John extends his explanation and others chime in with very useful notes.