使用所有向量元素的组合粘贴两个向量 [英] Pasting two vectors with combinations of all vectors' elements

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

问题描述

我有两个向量:

vars <- c("SR", "PL")
vis <- c(1,2,3)

基于这些向量,我想创建以下向量:

Based on these vectors I would like to create the following vector:

"SR.1"  "SR.2"  "SR.3"  "PL.1"  "PL.2"  "PL.3"

对于paste,我得到以下结果:

With paste I have the following result:

paste(vars, vis, sep=".")
 [1] "SR.1" "PL.2" "SR.3"

如何创建所需的载体?

推荐答案

您可以使用它,但是可能有一个更简单的解决方案:

You can use this, but there may be a simpler solution :

R> apply(expand.grid(vars, vis), 1, paste, collapse=".")
[1] "SR.1" "PL.1" "SR.2" "PL.2" "SR.3" "PL.3"


expand.grid返回一个data.frame,当与apply一起使用时,apply会将其转换为matrix.这只是不必要的(并且在大数据上效率低下). outer给出matrix并接受函数参数.在海量数据上也将非常有效.


expand.grid gives back a data.frame which when used with apply, apply will convert it to a matrix. This is just unnecessary (and inefficient on large data). outer gives a matrix and also takes function argument. It'll be much efficient on huge data as well.

使用outer:

as.vector(outer(vars, vis, paste, sep="."))
# [1] "SR.1" "PL.1" "SR.2" "PL.2" "SR.3" "PL.3"

这篇关于使用所有向量元素的组合粘贴两个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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