# [R] strsplit a matrix

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Mon Aug 10 19:29:01 CEST 2009

```one way us the following:

mat <- rbind(
c("2-271", "2-367", "1-79"),
c("2-282", "2-378", "1-90"),
c("2-281", "2-377", "1-89")
)

sp <- strsplit(c(mat), "-")
mat1 <- sapply(sp, "[", 1)
mat2 <- sapply(sp, "[", 2)
dim(mat1) <- dim(mat2) <- dim(mat)
mat1
mat2

I hope it helps.

Best,
Dimitris

James Perkins wrote:
> Dear all,
>
> I am trying to split a matrix into 2 as efficiently as possible.
>
> It is a character matrix:
>
>  1       2       3     1 "2-271" "2-367" "1-79"
> 2 "2-282" "2-378" "1-90"
> 3 "2-281" "2-377" "1-89"
>
> I want to make 2 matrices from this, as succinctly and efficiently as
> possible.
>
> I've tried such things as sapply(matrix, strsplit, "-") and tried to go
> from there, but I can't figure it out! So far I do it with a 2D for loop
> which can't be efficient!
>
> firstPartM <- matrix(ncol= dim(zzz)[2], nrow= dim(zzz)[1])
> secondPartM <- matrix(ncol= dim(zzz)[2], nrow= dim(zzz)[1])
> for(i in 1:dim(zzz)[1]) {
>   for(j in 1:dim(zzz)[2]) {
>     splitS <- strsplit(zzz[i,j],"-")
>     firstPartM[i,j] <- splitS[[1]][1]
>     secondPartM[i,j] <- splitS[[1]][2]
>   }
> }
>
> Cheers,
>
> Jim
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014

```