longtidue <- c('517W', '595W', '433W', '450E', '659E', '682W', '678W', '546E', '462W', '500W')
latitude <- c('291N','202N', '276N', '269S', '279N', '294N', '252N', '254S', '248N', '258N')
df <- data.frame(latitude, longitude)
is an example of a database that I'm working with that deals with coordinates in latitude and longitude that appear in the format:
240N, 707W, 267S, 130E
I need to process these coordinates so they can be used in a model that takes coordinates in the form:
24.0, -70.7, -26.7, 13.0
(In the model, North and East are considered the positive directions.)
The goal is to be able to run down the entire column, and to identify if there is either an "N" or an "S" in the cell. From there I want to remove the letter and then divide the remaining number by either 10 or -10 to give it the correct sign. If neither N or S appear in the column, I want the code to leave the cell alone, which is the reasoning for the else statement at the end of the sample code I've posted below. In order to process all the data in the columns, I've tried using an elseif statement but I wasn't exactly sure how to get it to work. I ended up at a for loop with if conditions that look like this:
for (i in 1:nrow(df)) {
if (grepl("N",df$latitude, fixed = TRUE)) {
df$latitude <- gsub("N", "",df$latitude) & df$latitude <- df$latitude/(10)
} else if (grepl("S",df$latitude, fixed = TRUE)) {
df$latitude <- gsub("S", "",df$latitude) & df$latitude <- as.numeric(df$latitude) & df$latitude <- df$latitude/(-10)
} else (df$latitude)
}
But this either gives me an error with df$latitude/(10) saying "non-numeric argument to binary operator" from the conversion of the data from character to numeric(?) and/or a warning that the "the condition has length > 1 and only the first element will be used". I'm also very new to R and stack overflow for that matter, so if my code could be formatted better, let me know.
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire