Remove character from string in R

帅比萌擦擦* 提交于 2019-12-11 08:03:28

问题


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",..

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

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

This isn't working.


回答1:


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.

Here is the data.

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

Here is the logic.

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

Here is the output

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


来源:https://stackoverflow.com/questions/42973681/remove-character-from-string-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!