0

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!

alistaire
  • 42,459
  • 4
  • 77
  • 117
Daxaniie
  • 65
  • 6
  • You seem not to return anything. Try adding `lonn` outside the if statements. I cannot test as I cannot donwload these packages(not my field). – NelsonGon Jan 31 '19 at 06:15
  • If you use `ifelse` instead of `if ... else`, your function will be vectorized, so you don't need to iterate with `*apply` at all. And the one you're looking for it `mapply` or `Map`. – alistaire Jan 31 '19 at 06:16
  • @alistaire Thank you, both the ifelse and mapply worked! – Daxaniie Jan 31 '19 at 06:58

0 Answers0