0

I have a variable called summed_EU_Sales, I want to get EU only.

I have tried to do it using gsub this way:

gsub(".*summed_", "", summed_EU_Sales)

which only removes the first summed_. I struggle to remove both of the sides.

lazlomeli
  • 61
  • 7
  • 2
    You may want to re-phrase your question, "_Remove everything before and after string_" sounds like you already know the string you'd like to keep, though most likely you want to strip off some parts matching a pattern. Or split input by underscore and extract 2nd item (`unlist(strsplit("summed_EU_Sales","_"))[2]`) – margusl Dec 19 '22 at 10:30

2 Answers2

1

Assuming your variable name summed_EU_Sales is actually a string "summed_EU_Sales", we can use regex groupings:

sub(".*_(EU)_.*", "\\1", "summed_EU_Sales")
#> [1] "EU"

Created on 2022-12-19 by the reprex package (v2.0.1)

TimTeaFan
  • 17,549
  • 4
  • 18
  • 39
0
library(stringr)
library(tidyverse)
x<-cbind.data.frame("summed_EU_Sales"=c(1:5),
                    "summed_jap_Sales"=c(1:5))
names(x) <- str_match(names(x), "_\\s*(.*?)\\s*_")[,2]
chris jude
  • 467
  • 3
  • 8