I am trying to apply a function to every row of a dataframe in R. I have already gone through several answers in Stack Overflow but they are not working.
Basically I have a dataframe of latitude and longitude information. The function, convertLngs2, takes in 3 inputs --> the column of longitude information from the dataframe, a source longitude and a destination longitude. If the difference between the source and destination longitude is greater than 180 degrees, all negative values in the longitude column need to be increased by 360 degrees.
library(dplyr)
library(geosphere)
# Source
latWaterloo <- 43.46687
lngWaterloo <- -80.52464
# Destination
latTaiwan <- 23.5983
lngTaiwan <- 120.8354
convertLngs2 <- function(lonn, srcLng, sonLng) {
diffr <- abs(srcLng) + abs(sonLng)
if (diffr > 180) {
if (lonn<0) {
lonn <- lonn + 360
} else {
lonn <- lonn
}
} else {
lonn <- lonn
}
}
geo_lines <- gcIntermediate(c(lngWaterloo, latWaterloo), c(lngTaiwan, latTaiwan), n=100, addStartEnd=T, sp=F)
geo_lines <- data.frame(geo_lines)
geo_lines2 <- geo_lines %>% mutate(lon=sapply(lon, convertLngs2(lon, lngWaterloo, lngTaiwan)))
geo_lines3 <- geo_lines %>% mutate(lon=convertLngs2(lon, lngWaterloo, lngTaiwan))
geo_lines4 <- geo_lines %>% mutate(lon=lapply(lon, convertLngs2(lon, lngWaterloo, lngTaiwan)))
geo_lines5 <- geo_lines %>% mutate(lon=apply(lon, 1, convertLngs2(lon, lngWaterloo, lngTaiwan)))
I need to keep the parameters of srcLng and sonLng in the function. I have tried sapply, lapply and apply but all of them give the following error:
Error in mutate_impl(.data, dots) :
Evaluation error: 'convertLngs2(lon, lngWaterloo, lngTaiwan)' is not a function, character or symbol.
In addition: Warning message:
In if (lonn < 0) { :
the condition has length > 1 and only the first element will be used
What changes are required for the code to work? Thanks!