从R中的字符串中删除字符 [英] Remove character from string in R

查看:1850
本文介绍了从R中的字符串中删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据框:

I have a data frame as given below:

data$Latitude
"+28.666428" "+28.666470" "+28.666376" "+28.666441" "+28.666330" "+28.666391"

str(data$Latitude)
Factor w/ 1368 levels "+10.037451","+10.037457",..

我想从每个纬度值中删除 +字符。
我尝试使用 gsub()

I want to remove the "+" character from each of the Latitude values. I tried using gsub()

data$Latitude<-gsub("+","",as.character(factor(data$Latitude)))

这不起作用。

推荐答案

您可以结合使用 sapply 子字符串 regexpr 来实现结果。

regexpr(< character>,< vector>)[1] 给出字符的索引。

使用该值作为<$ c $的起始索引c> substring ,其余字符串可以分开。

sapply 允许您循环访问值。

You can use a combination of sapply, substring and regexpr to achieve the result.
regexpr(<character>,<vector>)[1] gives you the index of the character.
Using the value as the start index for substring, the rest of the string can be separated.
sapply allows you loop through the values.

这里是数据。

d<-c("+28.666428","+28.666470","+28.666376","+28.666441","+28.666330")

这是逻辑。

v <- sapply(d, FUN = function(d){substring(d, regexpr('+',d) + 1, nchar(d))}, USE.NAMES=FALSE)  

这里是输出

> v
[1] "28.666428" "28.666470" "28.666376" "28.666441" "28.666330" "28.666391"

这篇关于从R中的字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆