Reputation: 8494
The following data frame represents latitude and longitude decimal coordinates. I wish to using + and - to show whether the decimal degrees are North, South, East or West (in the latitude and longitude column).
So, latitude would be positive if the decimal degrees were N. ... the latitude would be negative if the decimal degrees were S. ... the longitude would be positive if the decimal degrees were E and the longitude would be negative if the decimal degrees were W.
a <- c(1:3)
Lat <- c(54.5, 55.2, 10.1)
NS <- c("N","N","S")
Long <- c(1.2, 0.5, 1.3)
EW <- c("W","E","W")
df1 <- data.frame(a,Lat,NS,Long,EW)
How would I do this in R? Any advice would be much appreciated.
Upvotes: 4
Views: 2609
Reputation: 18759
Quite simply with ifelse
:
df2 <- data.frame(a=df1$a, Lat=ifelse(df1$NS=="N", df1$Lat, -1*df1$Lat),
Long=ifelse(df1$EW=="E", df1$Long, -1*df1$Long))
df2
a Lat Long
1 1 54.5 -1.2
2 2 55.2 0.5
3 3 -10.1 -1.3
Upvotes: 0
Reputation: 1789
See NMEA conversion: http://www.nmea.org/ but, you can do it in a for() method to get one by one position
Upvotes: 0
Reputation: 179558
Use ifelse
:
df1 <- within(df1, {
Lat <- ifelse(NS=="N", Lat, -Lat)
Long <- ifelse(EW=="E", Long, -Long)
})
df1
a Lat NS Long EW
1 1 54.5 N -1.2 W
2 2 55.2 N 0.5 E
3 3 -10.1 S -1.3 W
I use within()
to reduce the amount of typing.
Upvotes: 5