Created
April 9, 2019 08:31
-
-
Save lionel-/3951ff6ad628757d5c906d7c670f32bb to your computer and use it in GitHub Desktop.
Does a vector start with the same values as another vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I guess
starts_with()
should returnFALSE
instead of failing when length is shorter.