给出两个长度可变的向量,并且向量之间或向量内没有重复,如何有效地将向量按升序和交替顺序组合?
这里是一个例子:
mongodb://username:password@clusterName+port/yourdb?retryWrites=true&ssl=true&authSource=admin
预期输出为
a <- c(98, 101, 104, 136, 154, 193)
b <- c(31, 37, 41, 44, 48, 55, 80, 118, 179)
您可以看到我们从c(31, 98, 118, 136, 179, 193)
# b, a, b, a, b, a
的31开始,这是向量之间的最小值。
随后是a
中的98。然后从b
开始,下一个大于98的数字为118。依此类推,得出:
a
A = 98, 136, 193
B = 31, 118, 179
是否有更好的方法来解决此问题?
答案 0 :(得分:1)
您可以像这样使用data.frame
,order
和diff
:
a = c(98, 101, 104, 136, 154, 193)
b = c(31, 37, 41, 44, 48, 55, 80, 118, 179)
# Create a data frame for each vector with a different number in column 'set'
dfa = data.frame(val = a, set = 1)
dfb = data.frame(val = b, set = 2)
# Bind both together and order them by val
df = rbind(dfa,dfb)
df = df[order(df$val),]
# Only keep those that have a diff different to 0
keep = c(1, diff(df$set)) != 0
result = df[keep,]
结果:
val set
7 31 2
1 98 1
14 118 2
4 136 1
15 179 2
6 193 1
答案 1 :(得分:1)
您可以根据向量设置名称前缀,
v <- sort(c(setNames(a, paste0("a", a)), setNames(b, paste0("b", b))))
并使用diff
分解的初始字符。
res <- v[!!c(1, diff(as.numeric(as.factor(substr(names(v), 1, 1)))))]
res
# b31 a98 b118 a136 b179 a193
# 31 98 118 136 179 193
然后分成一个数据框:
d <- as.data.frame(split(res, substr(names(res), 1, 1)))
d
# a b
# a98 98 31
# a136 136 118
# a193 193 179
数据
a <- c(98, 101, 104, 136, 154, 193)
b <- c(31, 37, 41, 44, 48, 55, 80, 118, 179)