Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my line of code giving the wrong character location in a string

Tags:

string

r

I am working with a dataset where the data my variables column is in the format blah blah [text I actually want]. I have wrote a line to try to replace every data point in the variables column with a new data point with just text I actually want.

I thought I finally cracked it, but it does not seem to actually be working so far.

melted$variable = str_sub(
    melted$variable, start = gregexpr(
        pattern ="\\[",melted$variable)[1], end = (
            str_length(melted$variable) - 1
        )
    )

melted is my data set, and variable is the column name

like image 970
bensir Avatar asked Dec 04 '25 08:12

bensir


1 Answers

We can use sub and extract everything between [ and ]

sub(".*\\[(.*)\\].*", "\\1", x)
#[1] "ex1" "ex2"

Or using str_extract

stringr::str_extract(x, "(?<=\\[).*(?=\\])")
#[1] "ex1" "ex2"

where x is

x <- c("blah blah [ex1]", "blah blah [ex2]")

which can be replaced with melted$variable.

like image 93
Ronak Shah Avatar answered Dec 07 '25 05:12

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!