我有一个数据框 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")
Error: '\.' is an unrecognized escape in character string starting ""\."
的错误?代码如下:paste0('colnames(',AllDataTables[i],')<-','gsubfn("\\.x|\\.y", list(
.x="_Top",
.y= "_Bottom"), colnames(',AllDataTables[i], '))')
- sunitprasad1paste0('colnames(', ...)
。此外,你的代码中[i]
等内容很混乱。可能你正在引用循环中的某些东西。 - akrun