Skip to content

Instantly share code, notes, and snippets.

@lionel-
Created April 9, 2019 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lionel-/3951ff6ad628757d5c906d7c670f32bb to your computer and use it in GitHub Desktop.
Save lionel-/3951ff6ad628757d5c906d7c670f32bb to your computer and use it in GitHub Desktop.
Does a vector start with the same values as another vector
truncate_len <- function(x, n) {
if (length(x) < n) {
stop("Can't truncate vector to the given length because it is already shorter")
}
x[seq_len(n)]
}
truncate_along <- function(x, y) {
truncate_len(x, length(y))
}
starts_with <- function(x, y) {
x <- truncate_along(x, y)
all(x == y)
}
short <- setNames(1:10, letters[1:10])
long <- setNames(1:26, letters)
wrong <- rev(long)
truncate_along(long, short)
#> a b c d e f g h i j
#> 1 2 3 4 5 6 7 8 9 10
truncate_along(short, long)
#> Error in truncate_len(x, length(y)): Can't truncate vector to the given length because it is already shorter
starts_with(long, short)
#> [1] TRUE
starts_with(short, long)
#> Error in truncate_len(x, length(y)): Can't truncate vector to the given length because it is already shorter
starts_with(wrong, short)
#> [1] FALSE
starts_with(names(long), names(short))
#> [1] TRUE
starts_with(names(wrong), names(short))
#> [1] FALSE
starts_with(names(short), names(long))
#> Error in truncate_len(x, length(y)): Can't truncate vector to the given length because it is already shorter
Created on 2019-04-09 by the reprex package (v0.2.1.9000)
@lionel-
Copy link
Author

lionel- commented Apr 9, 2019

I guess starts_with() should return FALSE instead of failing when length is shorter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment