r - Removing all columns with a name on the fly -
i'm using read_excel
speed , simplicity import excel file.
unfortunately, there's yet no capability of excluding selected columns won't needed data set; save effort, naming such columns "x"
col_names
argument, easier trying keep track of x1
, x2
, , on.
i'd exclude such columns on fly if possible avoid step of copying, in pseudocode:
read_excel("data.xlsx", col_names = c("x", "keep", "x"))[ , !"x"]
we can use sample data set included readxl
package illustration:
library(readxl) df <- read_excel(system.file("extdata/datasets.xlsx", package = "readxl"), col_names = c("x", "x", "length", "width", "x"), skip = 1l)
the approaches i've seen work don't work on fly, e.g., having stored df
, can do:
df <- df[ , -grep("^x$", names(df))]
this works requires making copy of df
storing it, overwriting it; i'd prefer remove columns in same command read_excel
allocate df
ab initio.
other similar approaches require declaring temporary variables, prefer avoid if possible, e.g.,
col_names <- c("x", "x", "length", "width", "x") df <- read_excel(system.file("extdata/datasets.xlsx", package = "readxl"), col_names = col_names, skip = 1l)[ , -grep("^x$", col_names)]
is there way axe these columns without creating unnecessary temporary variables?
(i convert data.table
, wondering if there's way without data.table
)
there way in readxl::read_excel
, though it's little hidden, , have no idea if columns read memory [temporarily] regardless. trick specify column types, putting in "blank"
don't want:
readxl::read_excel(system.file("extdata/datasets.xlsx", package = "readxl"), col_types = c('blank', 'blank', 'numeric', 'numeric', 'text')) ## # tibble: 150 x 3 ## petal.length petal.width species ## <dbl> <dbl> <chr> ## 1 1.4 0.2 setosa ## 2 1.4 0.2 setosa ## 3 1.3 0.2 setosa ## 4 1.5 0.2 setosa ## 5 1.4 0.2 setosa ## 6 1.7 0.4 setosa ## 7 1.4 0.3 setosa ## 8 1.5 0.2 setosa ## 9 1.4 0.2 setosa ## 10 1.5 0.1 setosa ## # ... 140 more rows
the caveat need know data types of columns want, though suppose start text , clean later type.convert
or whatnot.
Comments
Post a Comment