[R] split() and paste() a vector to get a multi line string
Eric Lecoutre
lecoutre at stat.ucl.ac.be
Wed Dec 1 12:09:12 CET 2004
Hi:
here is something that works on your token.list object:
> paste(lapply(token.list,paste,collapse=", "),collapse="\n")
[1] "a, b, c\nd, e"
You can't use data.frames, as your vectors dont have the same number of
elements.
But you still have all the information, in a list. So you can use lapply to
compute on elements of this list.
If we decompose, the lapply does:
> lapply(token.list,paste,collapse=", ")
$"1"
[1] "a, b, c"
$"2"
[1] "d, e"
On which we call a paste.
HTH,
Eric
At 12:00 1/12/2004, Wolfram Fischer wrote:
>How can I get a multi line string from a vector of string tokens
>in an easy manner (e.g. for the use as xlab of a plot)?
>
>I have e.g.:
> > tokens <- letters[1:5]
>[1] "a" "b" "c" "d" "e"
>
>I search:
>[1] "a, b, c\nd, e"
>
>I tried:
> > nlines <- 2
> > ntokens.line <- ceiling(length(tokens) / nlines)
> > token.list <- split(tokens, rep( 1:ntokens.line,
> each=ntokens.line, len=length(tokens)))
>$"1"
>[1] "a" "b" "c"
>$"2"
>[1] "d" "e"
>
>I could work with a data.frame, e.g.:
> > paste(collapse='\n', apply(token.df, MARGIN=1, FUN=paste,
> collapse=', '))
>
>but I got an error when converting token.list to a data frame:
> > token.df <- data.frame( token.list )
>Error in data.frame("1" = c("a", "b", "c"), "2" = c("d", "e"), check.names
>= FALSE) :
> arguments imply differing number of rows: 3, 2
>
>What can I do (other than using a loop now)?
>
>Thanks - Wolfram
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Eric Lecoutre
UCL / Institut de Statistique
Voie du Roman Pays, 20
1348 Louvain-la-Neuve
Belgium
tel: (+32)(0)10473050
lecoutre at stat.ucl.ac.be
http://www.stat.ucl.ac.be/ISpersonnel/lecoutre
If the statistics are boring, then you've got the wrong numbers. -Edward
Tufte
More information about the R-help
mailing list