按字母顺序粘贴两个向量的元素 [英] Pasting elements of two vectors alphabetically
问题描述
假设我有两个向量:
a <- c("george", "harry", "harry", "chris", "steve", "steve", "steve", "harry")
b <- c("harry", "steve", "chris", "harry", "harry", "george", "chris", "george")
我想做的是将第一对、第二对等粘贴在一起......但是,我想按字母顺序粘贴每对的两个元素.在上面的例子中,前 2 对已经按字母顺序排列,但第三对 'harry' 和 'chris' 不是.我想回归克里斯·哈里"对于这一对.
What I want to do is paste together the 1st pair, 2nd pair, etc..... However, I want to paste the two elements of each pair in alphabetical order. In the above example, the first 2 pairs are already in alphabetical order, but the 3rd pair 'harry' and 'chris' are not. I want to return "chris harry" for this pair.
我已经在两步过程中找出了如何做到这一点,但想知道是否有一种快速的方法(单行方式)只使用 paste
来做到这一点?
I have worked out how to do this in a 2 step process, but was wondering if there was a quick way (one line way) to do this just using paste
?
我的解决方案:
x <- apply(mapply(c, a, b, USE.NAMES = FALSE), 2, sort)
paste(x[1,], x[2,])
按字母顺序给出对...但是有 1 行方式吗?
which gives the pairs in alphabetical order... but is there a 1 line way?
[1] "george harry" "harry steve" "chris harry" "chris harry" "harry steve" "george steve" "chris steve" "george harry"
推荐答案
这是一种方法:
apply(cbind(a, b), 1, function(x) paste(sort(x), collapse=" "))
## [1] "george harry" "harry steve" "chris harry" "chris harry"
## [5] "harry steve" "george steve" "chris steve" "george harry"
使用您最初的尝试,您还可以执行以下操作,但它们都需要更多的输入(不确定速度):
Using your initial attempt, you could also do the following but they both require more typing (not sure about speed):
unlist(Map(function(x, y) paste(sort(c(x, y)), collapse=" "), a, b),,FALSE)
mapply(function(x, y) paste(sort(c(x, y)), collapse=" "), a, b, USE.NAMES = FALSE)
这篇关于按字母顺序粘贴两个向量的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!