Conditionally Remove Character of a Vector Element in R

北慕城南 提交于 2019-12-23 03:12:32

问题


I have (sometimes incomplete) data on addresses that looks like this:

data <- c("1600 Pennsylvania Avenue, Washington DC", 
          ",Siem Reap,FC,", "11 Wall Street, New York, NY", ",Addis Ababa,FC,")  

I need to remove the first and/or last character if either one of them are a comma.

So far, I have:

for(i in 1:length(data)){
  lastchar <- nchar(data[i])
  sec2last <- nchar(data[i]) - 1
  if(regexpr(",",data[i])[1] == 1){
    data[i] <- substr(data[i],2, lastchar)
  }
  if(regexpr(",",data[i])[1] == nchar(data[i])){
    data[i] <- substr(data[i],1, sec2last)
  }
}

data

which works for the first character, but not the last character. How can I modify the second if statement or otherwise accomplish my goal?


回答1:


You could try the below code which remove the comma present at the start or at the end,

> data <- c("1600 Pennsylvania Avenue, Washington DC", 
+           ",Siem Reap,FC,", "11 Wall Street, New York, NY", ",Addis Ababa,FC,")
> gsub("(?<=^),|,(?=$)", "", data, perl=TRUE)
[1] "1600 Pennsylvania Avenue, Washington DC"
[2] "Siem Reap,FC"                           
[3] "11 Wall Street, New York, NY"           
[4] "Addis Ababa,FC" 

Pattern explanation:

  • (?<=^), In regex (?<=) called positive look-behind. In our case it asserts What precedes the comma must be a line start ^. So it matches the starting comma.
  • | Logical OR operator usually used to combine(ie, ORing) two regexes.
  • ,(?=$) Lookahead aseerts that what follows comma must be a line end $. So it matches the comma present at the line end.


来源:https://stackoverflow.com/questions/25432828/conditionally-remove-character-of-a-vector-element-in-r

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