How to subset data frame by column name like SAS in R? -


i have data frame x column names c("wk1","wk2","wk3",...,"wk100"), , want sum of week 40 week 60 each observation.

now in r i'm using grep function find position of wk40 , wk60 , summation:

sum(x[i,(grep(wk40,colnames(x)):grep(wk60,colnames(x))]) 

this fine, know in sas can use sum(of wk40-wk60). there better way in r?

in general base r not have such selection operator. subset() function allows such selections

sum(subset(x[i, ], select=wk40:wk60)) 

or row-wise sums @ once

rowsums(subset(x, select=wk40:wk60)) 

but can use literal values (no variables) it's pretty limited far coding against.

you use dplyr perform similar operation

x %>% select(b1:b3) %>% rowsums() 

Comments