[R] Data management problem: convert text string to matrix of 0's and 1's

Thomas Lumley tlumley at u.washington.edu
Thu Jan 26 19:40:24 CET 2006


On Thu, 26 Jan 2006, Dale Steele wrote:
> The data looks like:
> -->
> icsrvepf
> fpevrsci
> ics
> p
>
> f
> ic
> <--
>
> I would like to convert the about to a matrix of the form:
>
>  i c s r v e p f
>  1 1 1 1 1 1 1 1
>  1 1 1 1 1 1 1 1
>  1 1 1 0 0 0 0 0
>  0 0 0 0 0 0 1 0
>  0 0 0 0 0 0 0 0
>  0 0 0 0 0 0 0 1
>  1 1 0 0 0 0 0 0
>

One possibility is to use grep()
> a
[1] "icsrvepf" "fpevrsci" "p"        ""         "f"        "ic"
> grep("i",a)
[1] 1 2 6

so
> results<-matrix(0,nrow=length(a),ncol=length(behaviours))
> colnames(results)<-behaviours
> for(b in behaviours) results[grep(b,a),b]<-1
> results
      i c s r v e p f
[1,] 1 1 1 1 1 1 1 1
[2,] 1 1 1 1 1 1 1 1
[3,] 0 0 0 0 0 0 1 0
[4,] 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 1
[6,] 1 1 0 0 0 0 0 0
>

 	-thomas




More information about the R-help mailing list