Pasting two vectors with combinations of all vectors' elements
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
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.
Using outer
:
as.vector(outer(vars, vis, paste, sep="."))
# [1] "SR.1" "PL.1" "SR.2" "PL.2" "SR.3" "PL.3"
How to cross-paste all combinations of two vectors (each-to-each)?
You can also do:
outer(c("a", "b"), c("c", "d"), FUN = "paste0")[1:4]
[1] "ac" "bc" "ad" "bd"
Both do.call
and outer
are valuable functions to play with. :)
Alternately, we can assign
x <- outer(c("a", "b"), c("c", "d"), FUN = "paste0")
dim(x) <- NULL
x
[1] "ac" "bc" "ad" "bd"
Without knowing the length.
More edits!
x <- outer(c("a", "b"), c("c", "d"), FUN = "paste0")
y <- t(x)
dim(y) <- NULL
y
[1] "ac" "ad" "bc" "bd"
Gets you the desired order, too.
Paste all combinations of two separate vectors in R
Another approach:
df1 <- c("a","b","c")
df2 <- c("1","2","3")
apply(expand.grid(df1, df2), 1, paste, collapse="")
Paste all combinations of a vector in R
Try combn
combn(vec,2, FUN=paste, collapse='')
#[1] "AB" "AC" "BC"
Loop trough vector elements... and make new vector
no for-loops needed here.
sapply(combn(X, m = 2, simplify = FALSE), paste0, collapse = "-")
#"A-B" "A-C" "B-C"
How to create all the combinations in a vector using R
Something like this could work:
unlist(sapply(1:4, function(x) apply(combn(1:4, x), 2, paste, collapse = '')))
First we get the combinations using combn
and then we paste the outputs together. Finally, unlist gives us a vector with the output we need.
Output:
[1] "1" "2" "3" "4" "12" "13" "14" "23" "24" "34" "123" "124"
"134" "234" "1234"
Related Topics
Flip Ordering of Legend Without Altering Ordering in Plot
Dt[!(X == .)] and Dt[X != .] Treat Na in X Inconsistently
Ggplot2: Font Style in Label Expression
R: Sample() Command Subject to a Constraint
R * Not Meaningful for Factors Error
R Dplyr Rowwise Mean or Min and Other Methods
R: How to Use Coord_Cartesian on Facet_Grid with Free-Ranging Axis
Replace Missing Values (Na) in One Data Set with Values from Another Where Columns Match
R: Using a String as an Argument to Mutate Verb in Dplyr
Ggplot2: Reorder Bars from Highest to Lowest in Each Facet
Accessing Columns in Data.Table Using a Character Vector of Column Names
Dplyr Piping Data - Difference Between '.' and '.X'
Mutate Multiple Variable to Create Multiple New Variables
Find All Date Ranges for Overlapping Start and End Dates in R
Why Has Data.Table Defined := Rather Than Overloading <-
How to Retry a Statement on Error
How to Resolve Spherical Geometry Failures When Joining Spatial Data