How to replace a multiple pattern in a column name with corresponding multiple patterns in an R data.frame? -


i have data.frame datasample shown below :

   area category.x topsales category.y bottomsales 1  east    seafood 83220.19  beverages     2135.17 2 north  beverages 84324.99 condiments     2658.95 3 south  beverages 79202.89    seafood      400.00 4  west  beverages 70448.24 condiments     1563.60 

i wish replace category.x category_top , category.y category_bottom, tried following steps :

colnameold<-names(datasample)  colnamenew_1<-sub('.x','_top',colnameold)  colnamenew_2<-sub('.y','_bottom',colnamenew_1)  names(datasample)<-colnamenew_2 

and hence got required result, shown below.

   area category_top topsales category_bottom bottomsales 1  east    seafood   83220.19    beverages      2135.17 2 north  beverages   84324.99    condiments     2658.95 3 south  beverages   79202.89    seafood        400.00 4  west  beverages   70448.24    condiments     1563.60 

but question is, how can in single step, pass pattern of strings replaced , respective matching patterns, in separate vectors , use sub() or gsub() replace them?

my patterns ".x" , ".y" , replaced "_top" , "_bottom"


data sample:

structure(list(area = c("east", "north", "south", "west"), category.x = c("seafood",  "beverages", "beverages", "beverages"), topsales = c(83220.19,  84324.99, 79202.89, 70448.24), category.y = c("beverages", "condiments",  "seafood", "condiments"), bottomsales = c(2135.17, 2658.95, 400,  1563.6)), .names = c("area", "category.x", "topsales", "category.y",  "bottomsales"), row.names = c(na, -4l), class = "data.frame") 

you may use

library(gsubfn) colnames(datasample) <- gsubfn("(\\.(x|y))$", list(`.x`="_top",                     `.y`= "_bottom"), colnames(datasample)) colnames(datasample) #[1] "area"            "category_top"    "topsales"        "category_bottom" #[5] "bottomsales"     

or option mgsub

library(qdap) mgsub(c('\\.x$', '\\.y$'), c('_top', '_bottom'),                        colnames(datasample), fixed=false) #[1] "area"            "category_top"    "topsales"        "category_bottom" #[5] "bottomsales"  

update

if there list of 'data.frames'

 lst <- list(datasample, datasample)  lapply(lst, function(x) {colnames(x) <- gsubfn("(\\.(x|y))$",        list(`.x`="_top", `.y`= "_bottom"),  colnames(x))   x }) 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -