简体   繁体   中英

Create a combination of unique column names from two dataset without looping

I have two vectors:

a <- c(1,2,3)
b <- c(11,12,13)

I want to create a combination of column names (3*3 = 9) such that they use values from both:

paper1grid11 
paper1grid12
paper1grid13
paper2grid11
paper2grid12
paper2grid13
paper3grid11
paper3grid12
paper3grid13

I have tried using the paste0 command but that doesn't do a combination. Instead it just creates 3 column names.

paste0("paper", a,"grid", b)

I don't want to use a for loop

You can do this with expand.grid .

a <- c(1,2,3)
b <- c(11,12,13)
do.call(paste0, expand.grid("paper", a, "grid", b))

You can use outer , ie

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"

or wrap it around c to get the answer as a vector, ie

c(outer(a, b, function(x, y) paste0('paper', x, 'grid', y)))
#[1] "paper1grid11" "paper2grid11" "paper3grid11" "paper1grid12" "paper2grid12" "paper3grid12" "paper1grid13" "paper2grid13" "paper3grid13"

This post is tagged with data.table so here is a data.table solution:

CJ(a, b)[, paste0("paper", a, "grid", b)]

# [1] "paper1grid11" "paper2grid11" "paper3grid11" "paper1grid12" "paper2grid12"
# [6] "paper3grid12" "paper1grid13" "paper2grid13" "paper3grid13
apply(expand.grid("paper", a, "grid", b), 1, paste, collapse="")

You can use 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM