简体   繁体   English

如何从R中的字符串中仅删除“实际数字”

[英]How to remove only “actual numbers” from a string of characters in R

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, ie 1, 12, 123, but not the ones that are part of a character set, ie 2nd, C2, H2O. 我需要摆脱所有数字,即实际数字,即1,12,123,但不是那些属于字符集的数字,即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. 它成功地摆脱了1 12 123,同时保留了C2 H2O。 However, I lost 2 in 2nd. 但是,我在第二节输掉了2。

I am at my wits end. 我没办法。

Thanks! 谢谢!

Try this: 试试这个:

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

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. 如果需要,可以将结果paste到单个字符串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM