[R] how to divide a string into characters? - for comparing strings that is

David Andel andel at ifi.unizh.ch
Fri Jul 18 09:25:34 CEST 2003


Cool, thanks a lot!

On Thu, 17 Jul 2003, John Fox wrote:

> Dear David
>
> At 12:07 AM 7/18/2003 +0200, David Andel wrote:
>
> >I am searching for a way to do something like "ABC" -> c("A","B","C"). How
> >can this be accomplished?
> >
> >I tried cut() and split(), but they do something else, it seems.
> >
> >The purpose for doing this is to find the number of common (and uncommon)
> >characters, i.e. ultimately I want something like this:
> >
> > > foo("ABD","ADE")
> >c(2,1) # 2 in x are in y, 1 in y is not in x
> > > foo("AB","ADE")
> >c(1,2) # 1 in x is in y, 2 in y are not in x
> >
> >Maybe I even do not need the string splitting?
> >
> >I hope I was clear in stating my problem.
>
> Here's a solution based on splitting the strings:
>
>  > foo <- function(a, b){
> +     a <- strsplit(a, "")[[1]]
> +     b <- strsplit(b, "")[[1]]
> +     nmatch <- sum(outer(a, b, "=="))
> +     c(nmatch, length(b) - nmatch)
> +     }
>  > foo("ABD","ADE")
> [1] 2 1
>  > foo("AB","ADE")
> [1] 1 2
>
> By the way, apropos() turns up strsplit():
>
>  > apropos("split")
>   [1] "split"              "split.data.frame"   "split.data.frame<-"
>   [4] "split.default"      "split.screen"       "split<-"
>   [7] "split<-.data.frame" "split<-.default"    "strsplit"
> [10] "unsplit"
>
> I hope that this helps,
>   John
>
> -----------------------------------------------------
> John Fox
> Department of Sociology
> McMaster University
> Hamilton, Ontario, Canada L8S 4M4
> email: jfox at mcmaster.ca
> phone: 905-525-9140x23604
> web: www.socsci.mcmaster.ca/jfox
> -----------------------------------------------------
>

-- 
David Andel, MD-PhD Student, Artificial Intelligence Laboratory
Institute of Information Technology, University of Zurich
Andreasstrasse 15, 8050 Zurich, Switzerland
Phone: +41-1-635 45 75, Fax: +41-1-635 68 09, e-mail: andel at ifi.unizh.ch
Office: AND 2.18, Homepage: http://www.ifi.unizh.ch/~andel
--
"Real knowledge is to know the extent of ones ignorance." - Confucius
"Two wrongs don't make a right, but three lefts do."
"Democracy is not a spectator sport."




More information about the R-help mailing list