r-具有不相等向量和ID的公差的交集



我有一个关于两个向量之间的值匹配的问题。假设我有一个矢量和数据帧:

data.frame
value  name                       vector 2
154.0031  A                         154.0084
154.0768  B                         159.0344
154.2145  C                         154.0755
154.4954  D                         156.7758
156.7731  E
156.8399  F
159.0299  G
159.6555  H
159.9384  I

现在,我想将向量2与数据帧中具有定义的全局容差(例如+-0.005)的值进行比较,该全局容差是可调整的,并将相应的名称添加到向量2,因此我得到这样的结果:

data.frame
value  name                       vector 2 name
154.0031  A                         154.0074  A
154.0768  B                         159.0334  G
154.2145  C                         154.0755  B
154.4954  D                         156.7758  E
156.7731  E
156.8399  F
159.0299  G
159.6555  H
159.9384  I

我试着使用intersect(),但其中没有公差选项?

非常感谢!

此结果可以通过使用outerwhich和子集来实现。

# calculate distances between elements of each object
# rows are df and columns are vec 2
myDists <- outer(df$value, vec2, FUN=function(x, y) abs(x - y))

# get the values that have less than some given value
# using arr.ind =TRUE returns a matrix with the row and column positions
matches <- which(myDists < 0.05, arr.ind=TRUE)
data.frame(name = df$name[matches[, 1]], value=vec2[matches[, 2]])
name    value
1    A 154.0084
2    G 159.0344
3    B 154.0755
4    E 156.7758

请注意,这将只返回vec2中匹配的元素,并返回df中满足阈值的所有元素。

为了使结果对此具有稳健性,请使用

# get closest matches for each element of vec2
closest <- tapply(matches[,1], list(matches[,2]), min)
# fill in the names.
# NA will appear where there are no obs that meet the threshold.
data.frame(name = df$name[closest][match(as.integer(names(closest)),
seq_along(vec2))], value=vec2)

目前,这将返回与上面相同的结果,但将返回在df中没有足够观察到的NA。

数据

如果您将来提出问题,请提供可复制的数据。请参见下文。

df <- read.table(header=TRUE, text="value  name
154.0031  A
154.0768  B
154.2145  C
154.4954  D
156.7731  E
156.8399  F
159.0299  G
159.6555  H
159.9384  I")
vec2 <- c(154.0084, 159.0344, 154.0755, 156.7758)

最新更新