Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select multiple ranges of columns in data.table using column names [duplicate]

Tags:

r

data.table

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?

like image 894
AlexR Avatar asked Oct 18 '25 03:10

AlexR


2 Answers

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
like image 128
Remko Duursma Avatar answered Oct 19 '25 21:10

Remko Duursma


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

like image 37
NpT Avatar answered Oct 19 '25 20:10

NpT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!