I can select multiple ranges of columns in a data.table using a numeric vector like c(1:5,27:30)
. Is there any way to do the same with column names? For example, in some form similar to col1:col5,col27:col30
?
You can with dplyr
:
df <- data.frame(a=1, b=2, c=3, d=4, e=5, f=6, g=7)
dplyr::select(df, a:c, f:g)
a b c f g
1 2 3 6 7
I am not sure if my answer is efficient, but I think that could give you a workaround at least in case you need to work with data.table
.
My proposal is to use data.table
in conjunction with cbind
. Thus you could have:
df <- data.frame(a=1, b=2, c=3, d=4, e=5, f=6, g=7)
multColSelectedByName<- cbind(df[,a:c],df[,f:g])
#a b c f g
#1: 1 2 3 6 7
One point that one should be careful is that if there is only one column in one of the selections, for example df[,f]
then the name of this column would be something like V2
and not f
. In such a case one could use:
multColSelectedByName<- cbind(df[,a:c],f=df[,f])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With