gpt4 book ai didi

r - 测试短数值向量是否是 R 中长数值向量的一部分的函数

转载 作者:行者123 更新时间:2023-12-02 05:24:36 26 4
gpt4 key购买 nike

我正在尝试测试一个短数值向量是否是一个较长数值向量的一部分。例如,如果 a = c(2, 3)b = c(1, 3, 2, 4, 2, 3, 1),那么我是试图找到/想出一个函数来回答这个问题:ab 的一部分吗?输出应为 TRUE

或者,如果 c = c(1, 3, 2, 4, 1, 3, 1) 那么“的输出是 a 的一部分>c?"应该是 FALSE

match() 不做这个工作:

match(a, b)

返回

3  2

%in% 运算符也不行:

TRUE  TRUE

我知道有字符串匹配的选项,但我不想通过转换为字符串来解决这个问题...

最佳答案

这是我的绝招

valInLong <- function(val, long){
n.long <- length(long)
n.val <- length(val)
# Find where in the longer vector the first
# element of val is. This is so we can vectorize later
first <- which(long == val[1])
# If the first element is too near the end we don't care
# about it
first <- first[first <= n.long - n.val + 1]
# sequence from 0 to n.val - 1 used for grabbing subsequences
se <- seq_along(val)-1
# Look at all subsequences starting at 'first' that go
# the length of val and do an elementwise comparison.
# If any match in all positions then the subsequence is
# the sequence of interest.
any(sapply(first, function(x){all(long[x+se] == val)}))
}


long <- rpois(1000, 5)
a <- c(123421, 232, 23423) # probably not in long

valInLong(a, long)
a <- long[34:100]
valInLong(a, long)

关于r - 测试短数值向量是否是 R 中长数值向量的一部分的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28289361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com