简体   繁体   English

将 substring 移动到 R 中的字符串末尾

[英]Move substring to end of string in R

I have a set of df with a large number of columns.我有一组包含大量列的 df。 The column names follow a pattern like so:列名遵循如下模式:

my.df <- data.frame(sentiment_brand1_1 = c(1,0,0,1), sentiment_brand1_2 = c(0,1,1,0),
sentiment_brand2_1 = c(1,1,1,1),
sentiment_brand2_2 = c(0,0,0,0),
brand1_rating_1 = c(1,2,3,4),
brand2_rating_1 = c(4,3,2,1))

I'd like to programmatically rename the columns, moving the substrings "brand1" and "brand2" from the middle of the column name to the end, eg:我想以编程方式重命名列,将子字符串“brand1”和“brand2”从列名的中间移动到末尾,例如:

desired_colnames <- c("sentiment_1_brand1",
 "sentiment_2_brand1",
 "sentiment_1_brand2",
 "sentiment_2_brand2",
 "rating_1_brand1",
 "rating_1_brand2")

Capture the substring groups and rearrange in replacement捕获 substring 组并重新排列替换

 sub("(.*)_(brand1)(.*)", "\\1\\3_\\2", v1)

-output -输出

[1] "variable_1_brand1" "_stuff_1_brand1"   "thing_brand1"     

data数据

v1 <- c("variable_brand1_1", "_brand1_stuff_1", "_brand1thing")
## Input:
Test <- c("variable_brand1_1", "_brand1_stuff_1", "_brand1thing")

library("stringr")
paste(str_remove(Test, "_brand1"), "_brand1", sep = "")

## OutPut:
[1] "variable_1_brand1" "_stuff_1_brand1"   "thing_brand1"  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM