Skip to content

Instantly share code, notes, and snippets.

@TimTeaFan
Last active June 20, 2021 13:20
Show Gist options
  • Save TimTeaFan/74221343d1b6d264e931622c693bb8c2 to your computer and use it in GitHub Desktop.
Save TimTeaFan/74221343d1b6d264e931622c693bb8c2 to your computer and use it in GitHub Desktop.
seq_sum() function
seq_sum <- function(from, to, .sum, exact = FALSE) {
a <- from + to
m <- a/2
d <- .sum - a
if (exact && (d %% m !=0)) {
stop("sequence didn't converge.")
}
i <- (d / m) + 2
seq(from, to, length.out = i)
}
seq_sum(1, 5, 6)
#> 1 5
seq_sum(1, 5, 9)
#> 1 3 5
seq_sum(1, 5, 10)
#> 1.000000 2.333333 3.666667 5.000000
seq_sum(1, 5, 10, exact = TRUE)
#> Error in seq_sum(1, 5, 10, exact = TRUE) : sequence didn't converge.
seq_sum(1, 5, 15)
#> 1 2 3 4 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment