-1

I have a column name Food_Q_74 in a loop that becomes Food_Q_75 Food_Q_76 etc

I need to make it look like Q_74_A1, Q_75_A1 etc

I need to delete Food_ at the beginning and add _A1 at the end. So I am NOT adding a prefix as suggested. I am not only pasting at the end.

Any real help would be appreciated.

gsub('^Food_',' ',colnames(df$columns)) this deletes the Food_ but I can not figure out the code to add a suffix. Also, when I run that in R it does not change the column name. When I run it in the console it shows the deletion. ???

I thought ^ was for the start and $ for the end so I tried gsub('^Food_$ '',_A1',df$columns) but this is wrong.

aynber
  • 22,380
  • 8
  • 50
  • 63

4 Answers4

0

You could simply pasting the interim result together with "_A1":

without_food <- gsub('^Food_',' ',colnames(df$columns))

with_a1 <- paste0(without_food, "_A1")

An alternative to paste0 would be str_c from the stringr package.

deschen
  • 10,012
  • 3
  • 27
  • 50
0

To add something to a string (character), use the paste0-function.

namesWithoutFood <- gsub('^Food_',' ',colnames(df$columns))
paste0(namesWithoutFood,"_A1")
Jonas
  • 1,760
  • 1
  • 3
  • 12
0

You can do this all within gsub, without using paste:

gsub("^Food_(.*)$", "\\1_A1", colnames(df$columns))

The (.*)$ here means "Capture all characters after 'Food_' until the end of the string". The \\1_A in the replacement means "Use the captured group here and stick '_A' on the end."

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • That works perfectly in the console, thank you! gsub("^Food_(.*)$", "\\1_A1", colnames(finalmydat[,138:152])) [1] "Q_74_A1" "Q_75_A1" "Q_76_A1" "A_Q_77_1_A1" [5] "A_Q_77_2_A1" "A_Q_77_3_A1" "A_Q_77_4_A1" "A_Q_77_5_A1" [9] "A_Q_77_6_A1" "A_Q_77_7_A1" "A_Q_77_8_A1" "A_Q_77_9_A1" [13] "A_Q_77_10_A1" "A_Q_77_11_A1" "S_77_10_A1" But colnames(finalmydat[,138:152]) <- gsub("^Food_(.*)$", "\\1_A1", colnames(finalmydat[,138:152])) doesn't work when run. is my line of code incorrect? – Kirk Ammerman Dec 03 '20 at 14:20
0

had

colnames(finalmydat[,138:152])

but needed

colnames(finalmydat)[138:152]