R 具有不相等向量和ID公差的交点
我有一个关于匹配两个向量之间的值的问题。 假设我有一个向量和数据帧:R 具有不相等向量和ID公差的交点,r,vector,subset,intersection,assign,R,Vector,Subset,Intersection,Assign,我有一个关于匹配两个向量之间的值的问题。 假设我有一个向量和数据帧: data.frame value name vector 2 154.0031 A 154.0084 154.0768 B 159.0344 154.2145 C 154.0755 154.4954 D
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()
,但其中没有公差选项
非常感谢 这个结果可以通过
外部
,哪些
,以及子集来实现
# 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
#计算每个对象元素之间的距离
#行为df,列为vec 2
myDists谢谢,这很有帮助!对于数据方面,我将为将来的问题提供一个合适的数据集。
# 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 <- 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)