Pregunta

I have a string of numbers and characters

c2 = "list of 2nd C2 H2O 1 12 123"

I need to get rid of all digits that are actual numbers, i.e. 1, 12, 123, but not the ones that are part of a character set, i.e. 2nd, C2, H2O.

So far, the best solution I have come up with is this

gsub("? [[:digit:]]*", " ", c2)
"list of nd C2 H2O   "

It successfully gets rid of 1 12 123, while retaining C2 H2O. However, I lost 2 in 2nd.

I am at my wits end.

Thanks!

¿Fue útil?

Solución

Try this:

> gsub("\\b\\d+\\b", "", c2)
[1] "list of 2nd C2 H2O   "

Otros consejos

Here's a wacky approach which does not require regexp:

Rgames> c2 = "list of 2nd C2 H2O 1 12 123"
Rgames> sc2<-unlist(strsplit(c2,' '))
Rgames> nc2<-as.numeric(sc2)
Warning message:
NAs introduced by coercion 
Rgames> ssc2<-paste(sc2[is.na(nc2)])
Rgames> ssc2
[1] "list" "of"   "2nd"  "C2"   "H2O" 

If desired, one can paste that result into a single string.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top