简体   繁体   English

如何使用R删除字母

[英]How to delete letters using R

I would like to remove letters and symbols from a line using R, 我想使用R从一行中删除字母和符号,

temp <- " 20.9°C \n              a 07" 

everything from  to the end, and get only 从Â到最后的一切,仅获得

20.9

I have used this expression, but something fails... 我使用了这个表达式,但是失败了...

temp2 <- ( gsub("°C \n*?","", temp,  ignore.case = FALSE, perl = TRUE))

Since you state you only want 20.9 from your string and everything after removed, this will do the trick. 由于您声明只希望从字符串中删除20.9 ,并且删除后的所有内容都可以解决问题。

> temp <- ' 20.9°C \n              a 07'
> temp2 <- sub('^ (.*?)Â[^Â]+', '\\1', temp)
> temp2
## [1] "20.9"

If you end up needing to extract temperatures, you could start off with something like this: 如果最终需要提取温度,则可以从以下开始:

> library(gsubfn)
> temp <- ' -0.5°C \n \n   20.9°C      a +25.0°C'
> temp2 <- strapply(temp, '([+-]?[0-9]+\\.[0-9]+)')[[1]]
## [1] "-0.5"  "20.9"  "+25.0"

Based off your comment, how can I transform 25/08/14 to 25-08-2014 ? 根据您的评论,我如何将25/08/14转换为25-08-2014

gsub('([0-9]{2})/([0-9]{2})/([0-9]{2})', '\\1-\\2-20\\3', '25/08/14')
## [1] "25-08-2014"

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

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