Regular expression to replace a period (.) When appearing singly or with spaces, but not with a number with decimal point r

Given input vector (iv)

iv <- c(.10,.15,"hello","."," . ",". ")

I use:

out <- sub(regexp,NA,iv)

I need an output vector:

.10,.15,"hello",NA,NA,NA

but I don’t know how to form a regular expression to get what I need. Thanks in advance.

+5
source share
4 answers
  gsub('^\\s*[.]\\s*$', 'NA',c(.10,.15,"hello","."," . ",". "))
  [1] "0.1"   "0.15"  "hello" "NA"    "NA"    "NA"   

CHANGE replace ' NA' withNA

 gsub('^\\s*[.]\\s*$', NA,c(.10,.15,"hello","."," . ",". "))
[1] "0.1"   "0.15"  "hello" NA      NA      NA     

EDIT withstringr

library(stringr)
x <- c(.10,.15,"hello","."," . ",". ")
x[str_trim(x) == '.'] <- NA
x
[1] "0.1"   "0.15"  "hello" NA      NA      NA     
+2
source

What you are looking for is negative lookaheadin regular expressions. You want to check .what follows number (0-9)and replace them with NA. If you need this logic, then it can be implemented in 1 line as follows:

gsub("\\.(?![0-9])", NA, iv, perl=T)
# [1] "0.1"   "0.15"  "hello" NA      NA      NA     

: , , NA.

+4

NA, .

:

 iv[gsub(" ", "", iv)=="."] <- NA

:

(.. "."), iv[ iv=="."] <- NA.

, , "." .10, .15 .., , , ==.

, R, \., escape R, \\.


Edit: Note that the line above does not permanently remove spaces from iv. Take a look at gsub(" ", "", iv)=="."This returns the T / F vector, which in turn is used for filtering iv. In addition to the values NA, it ivremains unchanged.

EDIT # 2: If you want the changes to be saved on another vector, you can use the following:

 out <- iv
 out[gsub(" ", "", iv)=="."] <- NA
+3
source

Repeated expression:

       "^ *\. *$"
-1
source

All Articles