regular expressions

#1
I have the following two strings, which are N and W coordinates:

Code:
N <- c("59.22.07", "58.01.32", "57.26.49")

W <- c("02.26.45", "03.50.19", "07.24.15")
What I need are the two strings below. Presume this will need a regular expression, my knowledge of which is limited at present.

Code:
# needs last period removing
N <- c("59.2207", "58.0132", "57.2649")

# needs last period removing, plus a - at start
W <- c("-02.2645", "-03.5019", "-07.2415")
 

Dason

Ambassador to the humans
#2
A regex probably would work but to honest I'd probably just split the strings using strsplit and then create a function to combine the things the way you want them and then use sapply to use that function on each part of the list from strsplit.
Code:
> sapply(strsplit(N, "\\."), function(x){paste0(x[1], ".", x[2], x[3])})
[1] "59.2207" "58.0132" "57.2649"
> sapply(strsplit(W, "\\."), function(x){paste0("-", x[1], ".", x[2], x[3])})
[1] "-02.2645" "-03.5019" "-07.2415"
 

trinker

ggplot2orBust
#3
I'm curious on how to do this with a negative look ahead. I tried:

Code:
gsub("(!?\\.)", "", N)
gsub("([\\.]?!)", "", N)
But was not successful.
 

trinker

ggplot2orBust
#5
Great responses:

Code:
N <- c("59.22.07", "58.01.32", "57.26.49")

gsub("(.*)\\.", "\\1", N)
gsub("(.*)0", "\\1", N)[COLOR="gray"]#works with the 0s as well[/COLOR]
 
#6
A regex probably would work but to honest I'd probably just split the strings using strsplit and then create a function to combine the things the way you want them and then use sapply to use that function on each part of the list from strsplit.
Code:
> sapply(strsplit(N, "\\."), function(x){paste0(x[1], ".", x[2], x[3])})
[1] "59.2207" "58.0132" "57.2649"
> sapply(strsplit(W, "\\."), function(x){paste0("-", x[1], ".", x[2], x[3])})
[1] "-02.2645" "-03.5019" "-07.2415"
I was expecting 'paste0' to throw an error - this is a a new one for me. So paste0 simply saves having to type sep=''. Is that right?
 

Dason

Ambassador to the humans
#7
I was expecting 'paste0' to throw an error - this is a a new one for me. So paste0 simply saves having to type sep=''. Is that right?
Yup. paste0 was introducted with 2.15 basically to save a lot of people a little bit of typing. At this point they can't change the default to paste but since a lot of people thought it would be nicer if the default separator was just no spaces they added paste0.