search for column names from an array in R -
the columns in data frame called col_rent, col_oil etc
i have list of words in array below. if precede of these "col_", column name.
> listofwords [1] "rent" [2] "pay" [3] "oil" [4] "gas" [5] "food"
i find index of each of these columns.
i tried grep follows, want find column numbers of col_rent, col_pay, col_oil, col_gas, col_food without using loop
> grep(paste0("cm_",listofwords),names(dfread)) [1] 359 warning message: in grep(paste0("cm_", listofwords), names(dfread)) : argument 'pattern' has length > 1 , first element used
however, message says, not allow me grep each member of list. how can end list of numbers, each showing column name these columns occur in data frame.
maybe should vectorize operation:
sapply(paste0("cm_",listofwords), function( element ) { grep(element,names(dfread)) })
it works me this:
> listofwords <-c( "rent", + "pay", + "oil", + "gas", + "food") > as.array(listofwords) [1] "rent" "pay" "oil" "gas" "food" > dfread <- data.frame( cm_pay = 0, + cm_rent = 1, + cm_aaa1 = 3, + cm_oil = 2, + cm_aaa2 = 7, + cm_gas = 8, + cm_food = 9 + ) > colnames(dfread) [1] "cm_pay" "cm_rent" "cm_aaa1" "cm_oil" "cm_aaa2" "cm_gas" "cm_food" > sapply(paste0("cm_",listofwords), function( element ) { + grep(element,names(dfread)) + }) cm_rent cm_pay cm_oil cm_gas cm_food 2 1 4 6 7
Comments
Post a Comment