Notslayer205
Notslayer205

Reputation: 19

How to loop over each element of a list with another element of another list in R

I have to 2 list such as follow:

List1 <- c("X", "Y","Z")
List2 <- c("Enable", "Status", "Quality")

I am expecting something like this:

X_Enable, X_Status,X_Quality,Y_Enable, Y_Status,Y_Quality, Z_Enable, Z_Status,Z_Quality.

Any recommendation will be helpful for me.Thank you

Upvotes: 2

Views: 52

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101189

We can use interaction like below

> levels(interaction(List1, List2, sep = "_"))
[1] "X_Enable"  "Y_Enable"  "Z_Enable"  "X_Quality" "Y_Quality" "Z_Quality"
[7] "X_Status"  "Y_Status"  "Z_Status"

or expand.grid

> do.call(paste, c(expand.grid(List1, List2), sep = "_"))
[1] "X_Enable"  "Y_Enable"  "Z_Enable"  "X_Status"  "Y_Status"  "Z_Status"
[7] "X_Quality" "Y_Quality" "Z_Quality"

Upvotes: 1

akrun
akrun

Reputation: 887028

We may use outer

c(outer(List1, List2, FUN = function(x, y) paste(x, y, sep = "_")))

Upvotes: 2

Vin&#237;cius F&#233;lix
Vin&#237;cius F&#233;lix

Reputation: 8811

Here a way to do it:

Data

List1 <- c("X", "Y","Z")
List2 <- c("Enable", "Status", "Quality")

Code

paste(rep(List1,each = length(List2)),List2,sep = "_")

Output

[1] "X_Enable"  "X_Status"  "X_Quality" "Y_Enable"  "Y_Status"  "Y_Quality" "Z_Enable"  "Z_Status"  "Z_Quality"

Upvotes: 5

Related Questions