粘贴网格-expand.grid用于字符串连接 [英] paste grid -- expand.grid for string concatenation

查看:56
本文介绍了粘贴网格-expand.grid用于字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要获取两个向量的所有组合,可以使用 rep /回收规则:

If we want to get all combinations of two vectors, we can use rep/recycling rules:

x <- 1:4
y <- 1:2

cbind(rep(x, each = length(y)), rep(y, length(x)))
#      [,1] [,2]
# [1,]    1    1
# [2,]    1    2
# [3,]    2    1
# [4,]    2    2
# [5,]    3    1
# [6,]    3    2
# [7,]    4    1
# [8,]    4    2

但是 expand.grid 更好-它为我们处理了所有重复。

But expand.grid is much nicer -- it handles all the repetition for us.

expand.grid(x, y)
#   Var1 Var2
# 1    1    1
# 2    2    1
# 3    3    1
# 4    4    1
# 5    1    2
# 6    2    2
# 7    3    2
# 8    4    2

是否有用于连接字符串的简单版本?像 paste.grid 一样?我有一个命名对象,其中很多对象的名称都像 x_y_z ,其中 x y z 就像 x y

Is there a simple version of this for concatenating strings? Like paste.grid? I have a named object where a lot of the objects have names like x_y_z where x, y, and z vary like x and y above.

例如,假设 x 可以为 avg 中位数 y 可以是男性 女性 z 可以为身高 体重

For example, suppose x can be "avg" or "median", y can be "male" or "female", and z can be "height" or "weight". How can we concisely get all 8 combinations of the three?

使用 rep 是一件很痛苦的事情:

Using rep is a pain:

x <- c("avg", "median")
y <- c("male", "female")
z <- c("height", "weight")
paste(rep(x, each = length(y) * length(z)),
      rep(rep(y, each = length(z)), length(x)),
      rep(z, length(x) * length(y)), sep = "_")

重新使用 expand.grid 有点笨拙(可能效率很低):

And repurposing expand.grid is a bit clunky (and probably inefficient):

apply(expand.grid(x, y, z), 1, paste, collapse = "_")

我错过了什么吗?有没有更好的方法?

Am I missing something? Is there a better way to do this?

推荐答案

是的,这就是交互确实

levels(interaction(x,y,z,sep='_'))

实现与您的 rep 代码几乎相同。

The implementation is pretty much the same as your rep code.

输出:


[1] "avg_female_height"    "median_female_height" "avg_male_height"      "median_male_height"   "avg_female_weight"   
[6] "median_female_weight" "avg_male_weight"      "median_male_weight"  

这篇关于粘贴网格-expand.grid用于字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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