IVIM
IVIM

Reputation: 2367

how to remove N-th character from string in R?

Q1) Very simple. I have

a <- "* 3.45"

I need to remove the first and second character, so I have

b <- "3.45"

How do I do that?

Q2) A more generic question : How to remove all non-digit characters in front of digits in a character string? So if I have "%$aqs -3.45", I'll get "-3.45"?

Upvotes: 3

Views: 1736

Answers (2)

MrFlick
MrFlick

Reputation: 206566

If you want to remove "non-digit character" in front of numbers, you can use some regular expressions

a <- "* 3.45"
b <- "%$aqs -3.45"
gsub("^[^0-9.-]+", "", a)
# [1] "3.45"
gsub("^[^0-9.-]+", "", b)
# [1] "-3.45"

here we remove anything at the start of a string that's not a digit, decimal point, or minus sign.

Upvotes: 2

tmfmnk
tmfmnk

Reputation: 40171

For the first part, you can do:

substr(a, 3, nchar(a))

[1] "3.45"

Or:

substring(a, 3)

Upvotes: 2

Related Questions