I remember a comment on r-help in 2001 saying that drop = TRUE
in [.data.frame
was the worst design decision in R history.
dplyr
corrects that and does not drop implicitly. When trying to convert old code to dplyr
style, this introduces some nasty bugs when d[, 1]
or d[1]
is assumed a vector.
My current workaround uses unlist
as shown below to obtain a 1-column vector. Any better ideas?
library(dplyr)
d2 = data.frame(x = 1:5, y = (1:5) ^ 2)
str(d2[,1]) # implicit drop = TRUE
# int [1:5] 1 2 3 4 5
str(d2[,1, drop = FALSE])
# data.frame': 5 obs. of 1 variable:
# $ x: int 1 2 3 4 5
# With dplyr functions
d1 = data_frame(x = 1:5, y = x ^ 2)
str(d1[,1])
# Classes ‘tbl_df’ and 'data.frame': 5 obs. of 1 variable:
# $ x: int 1 2 3 4 5
str(unlist(d1[,1]))
# This ugly construct gives the same as str(d2[,1])
str(d1[,1][[1]])
You can just use the
[[
extract function instead of[
.If you use a lot of piping with dplyr, you may also want to use the convenience functions
extract
andextract2
from themagrittr
package:Or if
extract
is too verbose for you, you can just use[
directly in the pipe: