[R] creating possible cominations of a vector's elements
David L Carlson
dcarlson at tamu.edu
Fri Dec 9 02:12:22 CET 2016
This corrects an error in my earlier function definition:
makestrings <- function(vec) {
len <- length(mystring.spl)
idx <- expand.grid(1:len, 1:len)
idx <- idx[idx$Var2 <= idx$Var1, c("Var2", "Var1")]
mapply(function(x, y) paste(vec[x:y], collapse=" "),
x=idx[, 1], y=idx[, 2])
}
David C
-----Original Message-----
From: David L Carlson
Sent: Thursday, December 8, 2016 5:51 PM
To: 'Dimitri Liakhovitski' <dimitri.liakhovitski at gmail.com>; r-help <r-help at r-project.org>
Subject: RE: [R] creating possible cominations of a vector's elements
You can use expand.grid() and mapply():
mystring <- "this is my vector"
mystring.spl <- strsplit(mystring, " ")[[1]]
makestrings <- function(x) {
len <- length(mystring.spl)
idx <- expand.grid(1:len, 1:len)
idx <- idx[idx$Var2 <= idx$Var1, c("Var2", "Var1")]
mapply(function(x, y) paste(mystring.spl[x:y], collapse=" "),
x=idx[, 1], y=idx[, 2])
}
makestrings(mystring.spl)
[1] "this" "this is" "this is my"
[4] "this is my vector" "is" "is my"
[7] "is my vector" "my" "my vector"
[10] "vector"
This makes a vector of strings but if you want a list use as.list(mapply())
David L. Carlson
Department of Anthropology
Texas A&M University
-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Dimitri Liakhovitski
Sent: Thursday, December 8, 2016 5:03 PM
To: r-help <r-help at r-project.org>
Subject: [R] creating possible cominations of a vector's elements
Hello!
I have a vector of strings 'x' that was based on a longer string
'mystring' (the actual length of x is unknown).
mystring <- "this is my vector"
x <- strsplit(mystr, " ")[[1]]
I am looking for an elegant way of creating an object (e.g., a list)
that contains the following strings:
"this"
"this is"
"this is my"
"this is my vector"
"is"
"is my"
"is my vector"
"my"
"my vector"
"vector"
Thanks a lot!
--
Dimitri
______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list