Skip to content

How to get a matrix by sapply (with strsplit)?

3 messages · Peng Yu, Steve Lianoglou, Hadley Wickham

#
I want a command (last line) that can return a matrix. I'm wondering
if there is a way to do so.

g<-function(x) {
  c(x,x)
}
lapply(1:10,g)
sapply(1:10,g)

sapply(paste(1:10, 1:10), strsplit, split=' ')# I want a command that
returns a matrix
#
Hi,
On Dec 4, 2009, at 12:10 AM, Peng Yu wrote:

            
I'm not sure what the other lines(but the last) have to do anything, but are you looking for something like this:

do.call(rbind, sapply(paste(1:10, 1:10), strsplit, split=' '))

or:

do.call(cbind, sapply(paste(1:10, 1:10), strsplit, split=' '))

?

-steve

--
Steve Lianoglou
Graduate Student: Computational Systems Biology
  |  Memorial Sloan-Kettering Cancer Center
  |  Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact
#
strsplit is already vectorised wrt its first argument, so all you need is:

do.call(rbind, strsplit(paste(1:10, 1:10), split=' '))

Alternatively, you can use str_split_fixed from the stringr package:

library(stringr)
str_split_fixed(paste(1:10, 1:10), " ", 2)

Hadley