[R] "unsparse" a vector

Petr Savicky savicky at cs.cas.cz
Wed Feb 8 22:32:09 CET 2012


On Wed, Feb 08, 2012 at 03:56:12PM -0500, Sam Steingold wrote:
> To be clear, I can do that with nested for loops:
> 
> v <- c("A1B2","A3C4","B5","C6A7B8")
> l <- strsplit(gsub("(.{2})","\\1,",v),",")
> d <- data.frame(A=vector(length=4,mode="integer"),
>                 B=vector(length=4,mode="integer"),
>                 C=vector(length=4,mode="integer"))
> 
> for (i in 1:length(l)) {
>   l1 <- l[[i]]
>   for (j in 1:length(l1)) {
>     d[[substring(l1[j],1,1)]][i] <- as.numeric(substring(l1[j],2,2))
>   }
> }

Hi.

The inner loop may be vectorized.

  d <- as.matrix(d)
  for (i in 1:length(l)) {
    l1 <- l[[i]]
    d[i, substring(l1,1,1)] <- as.numeric(substring(l1,2,2))
  }

    A B C
  1 1 2 0
  2 3 0 4
  3 0 5 0
  4 7 8 6

If the number of rows of d is large, a matrix is probably
more efficient.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list