rfunctionloopspackagegeosphere

How do I loop a specific function from a package in r?


I have list of dates like this.

OnlyDates [1] "2018-01-22" "2018-01-22" "2018-01-22" "2018-01-22" "2018-01-22" "2018-01-22" "2018-01-22" "2018-01-22" "2018-01-22" "2018-01-22" "2018-01-22" [353] "2018-09-25" "2018-09-25" "2018-09-25" "2018-09-25" "2018-09-25" "2018-09-25" "2018-09-25" "2018-09-25" "2018-10-10" "2018-10-10" "2018-10-10" [364] "2018-10-10" "2018-10-10" "2018-10-10" "2018-10-10" "2018-10-10" "2018-10-10" "2018-10-10" "2018-10-10" "2018-10-10" "2018-10-10" "2018-10-10"

I want to loop a function that calculates hours of photoperiod in a specific day, and prints it in another column called "Photoperiod". The function is called 'daylength', from the package 'geosphere'

The am trying something like this:

for (i in OnlyDates {print(daylength(-43.39, "i"))})

-43.39 is the latitude, and "i" should be the date written as: "2021-08-05"

Example of the function alone:

daylength(-43.39, "2021-08-05")

Which returns [1] 9.897292

Instead, with my code I get:

Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'print': character string is not in a standard unambiguous format

Anyone can give some light on this? Thanks, Leo


Solution

  • use i (not "i") without quotation mark.

    besides bracket in for loop is in wrong place. you should end iteration condition first, then define body

    for (i in OnlyDates) {print(daylength(-43.39, i))}