Best practice to get a dropped column in dplyr tbl_df

845 Views Asked by At

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]])
1

There are 1 best solutions below

5
On BEST ANSWER

You can just use the [[ extract function instead of [.

d1[[1]]
## [1] 1 2 3 4 5

If you use a lot of piping with dplyr, you may also want to use the convenience functions extract and extract2 from the magrittr package:

d1 %>% magrittr::extract(1) %>% str
## Classes ‘tbl_df’ and 'data.frame':  5 obs. of  1 variable:
##   $ x: int  1 2 3 4 5
d1 %>% magrittr::extract2(1) %>% str
##  int [1:5] 1 2 3 4 5

Or if extract is too verbose for you, you can just use [ directly in the pipe:

d1 %>% `[`(1) %>% str
## Classes ‘tbl_df’ and 'data.frame':  5 obs. of  1 variable:
##   $ x: int  1 2 3 4 5
d1 %>% `[[`(1) %>% str
##  int [1:5] 1 2 3 4 5