如何用R data.frame中的相应多个模式替换列名中的多个模式?

时间:2015-07-14 08:23:11

标签: r

我有一个data.frame DataSample,如下所示:

   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

我希望将Category.x替换为Category_Top,将Category.y替换为Category_Bottom,所以我尝试了以下步骤:

ColNameOld<-names(DataSample)

ColNameNew_1<-sub('.x','_Top',ColNameOld)

ColNameNew_2<-sub('.y','_Bottom',ColNameNew_1)

names(DataSample)<-ColNameNew_2

因此我得到了所需的结果,如下所示。

   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

但我的问题是,如何在一个步骤中执行此操作,我在单独的向量中传递要替换的字符串模式和各自的匹配模式,并使用sub()gsub()替换他们?

我的模式总是“.x”和“。y”,并被“_Top”和“_Bottom”取代

数据样本:

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

1 个答案:

答案 0 :(得分:6)

您可以使用

cmake -E date [format] [UTC]

或另一个选项是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"

mgsub

更新

如果有library(qdap) mgsub(c('\\.x$', '\\.y$'), c('_Top', '_Bottom'), colnames(DataSample), fixed=FALSE) #[1] "Area" "Category_Top" "TopSales" "Category_Bottom" #[5] "BottomSales" 'data.frames'

list