[R] how to divide a string into characters? - for comparing strings that is
John Fox
jfox at mcmaster.ca
Fri Jul 18 00:55:14 CEST 2003
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
More information about the R-help
mailing list