简体   繁体   中英

Conditional changes of values in a column R

I'm trying to change the values in my Latitude and Longitude columns. Instead of South (in latitude), I want to drop the S and make the number negative. If it is North, I just want to drop the N. I would like to do the same thing with Longitude, and drop the letters. I want West to be negative and East be positive.

Here is a snip of my data frame

Please let me know how I can accomplish this!

For a data frame defined as df

# build a sample data frame with two columns, lat and long
df <- data.frame(Lat = c("1.2N", "1.2S", "35.5N", "33.4S"),
                 Long = c("113.8W", "113.5W", "43.2E", "55.4E"))

# use gsub with signature gsub(PATTERN, REPLACEMENT, X)
# where you use a regex for the pattern and replacement
# and X is your target.
df$Lat <- gsub("(\\d*\\.\\d*)N","\\1", df$Lat, perl = TRUE)
df$Lat <- gsub("(\\d*\\.\\d*)S","-\\1", df$Lat, perl = TRUE)
df$Long <- gsub("(\\d*\\.\\d*)W","\\1", df$Long, perl = TRUE)
df$Long <- gsub("(\\d*\\.\\d*)E","-\\1", df$Long, perl = TRUE)

So now the only work left is to work out the regex, which isn't anything special to R, save that what you would use as \\w anywhere else, in R you need to turn into \\\\w , etc.

So, we want to match digits, so a single regex digit is (in R) \\\\d , so we want to capture all of them before and after our decimal, which means

\\d*.\\d*

but that . is special in regex, so let's escape it for

\\d*\\.\\d*

Now let's think of the N , and we want to remove that in the replacement, so we need to group the digits so that we keep them in our match. We do this with parentheses. So, one group and the letter gives us

(\\d*\\.\\d*)N

we can refer to the captured group in our replacement with \\\\1 . So our replacement regex is simply

\\1 which really means \\d*\\.\\d*

and similarly for the S, where we add a - to the front of each match with

-\\1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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