我有两个向量:
a <- c(1,2,3)
b <- c(11,12,13)
我想创建一个列名(3 * 3 = 9)的组合,以便它们使用两个列中的值:
paper1grid11
paper1grid12
paper1grid13
paper2grid11
paper2grid12
paper2grid13
paper3grid11
paper3grid12
paper3grid13
我尝试使用paste0命令,但是没有结合使用。而是只创建3个列名。
paste0("paper", a,"grid", b)
我不想使用for循环
答案 0 :(得分:6)
您可以使用expand.grid
进行此操作。
a <- c(1,2,3)
b <- c(11,12,13)
do.call(paste0, expand.grid("paper", a, "grid", b))
答案 1 :(得分:4)
您可以使用outer
,即
outer(a, b, function(x, y) paste0('paper', x, 'grid', y))
# [,1] [,2] [,3]
#[1,] "paper1grid11" "paper1grid12" "paper1grid13"
#[2,] "paper2grid11" "paper2grid12" "paper2grid13"
#[3,] "paper3grid11" "paper3grid12" "paper3grid13"
或将其包装在c
周围以得到答案作为矢量,即
c(outer(a, b, function(x, y) paste0('paper', x, 'grid', y)))
#[1] "paper1grid11" "paper2grid11" "paper3grid11" "paper1grid12" "paper2grid12" "paper3grid12" "paper1grid13" "paper2grid13" "paper3grid13"
答案 2 :(得分:3)
此帖子被标记为data.table
,因此这是一个data.table
解决方案:
CJ(a, b)[, paste0("paper", a, "grid", b)]
# [1] "paper1grid11" "paper2grid11" "paper3grid11" "paper1grid12" "paper2grid12"
# [6] "paper3grid12" "paper1grid13" "paper2grid13" "paper3grid13
答案 3 :(得分:1)
uint32_t
答案 4 :(得分:1)
您可以使用crossing()
library(tidyverse)
crossing("paper",a,"grid",b)%>%unite(`"paper"`,a,`"grid"`,b, col = "col1",sep="")%>%pull(col1)
[1] "paper1grid11" "paper1grid12" "paper1grid13" "paper2grid11" "paper2grid12" "paper2grid13"
[7] "paper3grid11" "paper3grid12" "paper3grid13"