[R] Substring a column vector

Dennis Murphy djmuser at gmail.com
Thu Jul 7 06:36:37 CEST 2011


Hi:

Here's one take:

shalve <- function(x) {
   nc <- sapply(x, nchar)
   ns <- nc %/% 2
   cbind(a1 = substring(x, 1, ns),
        a2 = substring(x, ns + 1, nc))
  }
> shalve(a)
     a1    a2
[1,] "1"   "1"
[2,] "1"   "2"
[3,] "12"  "34"
[4,] "12"  "45"
[5,] "124" "567"
[6,] "126" "786"
[7,] "145" "769"

HTH,
Dennis

On Wed, Jul 6, 2011 at 8:41 PM, Peter Maclean <pmaclean2011 at yahoo.com> wrote:
> How to substring the following vector (in data frame b)
>>b
> a
> 11
> 12
> 1234
> 1245
> 124567
> 126786
> 145769
>
> such that:
>
> a1    a2
> 1     1
> 1     2
> 12    23
> 12    34
> 124   567
> 126   787
> 145   769
> I tried logical commands with substr() did not work out.
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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