按字母顺序粘贴两个向量的元素 [英] Pasting elements of two vectors alphabetically

查看:74
本文介绍了按字母顺序粘贴两个向量的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个向量:

a <- c("george", "harry", "harry", "chris", "steve", "steve", "steve", "harry")
b <- c("harry", "steve", "chris", "harry", "harry", "george", "chris", "george")

我想要做的是将第一对,第二对等粘贴在一起...但是,我想按字母顺序粘贴每对中的两个元素.在上面的示例中,前2对已经按字母顺序排列,但第3对"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆