[R] split() and paste() a vector to get a multi line string

Wolfram Fischer wolfram at fischer-zim.ch
Wed Dec 1 12:00:20 CET 2004


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




More information about the R-help mailing list