I have a dataframe df with column names from m1 to m100
I want to delete columns in the range m50 to m100. Is there a faster way to do it than hardcoding it
Assuming you have something like:
mydf <- data.frame(matrix(1:100, ncol = 100,
dimnames = list(NULL, paste0("m", 1:100))))
Simply do:
mydf[paste0("m", 50:100)] <- list(NULL) ## This is pretty destructive ;-)
By the way, you can also do:
subset(mydf, select = m1:m49)
or
subset(mydf, select = -(m50:m100))
With dplyr you could do it like this:
library(dplyr)
df <- select(df, -(M50:M100))
This removes all columns between column "M50" and column "M100".
A different option, that does not depend on the order of columns is to use
df <- select(df, -num_range("M", 50:100))
More eloquently put, without using any external packages or extra function calls, just use R's logical subsets:
mydf <- data.frame(matrix(1:100, ncol = 100,
dimnames = list(NULL, paste0("M", 1:100))))
mydf[,1:49]
yielding:
> mydf[,1:49]
m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14 m15 m16 m17 m18 m19 m20 m21 m22
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
m23 m24 m25 m26 m27 m28 m29 m30 m31 m32 m33 m34 m35 m36 m37 m38 m39 m40 m41 m42
1 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
m43 m44 m45 m46 m47 m48 m49
1 43 44 45 46 47 48 49
We can assign the columns to NULL in data.table
library(data.table)
setDT(df_cohort)[, paste0('M', 50:100) := NULL]
If we need to subset,
setDT(df_cohort)[, setdiff(names(df_cohort),
paste0('m', 50:100)), with=FALSE]