[R] sapply/lapply instead of loop

jim holtman jholtman at gmail.com
Tue Aug 10 21:05:20 CEST 2010


will this do what you want:

> newTemp[] <- lapply(newTemp, function(.col){
+     # convert to character and pad to 5 space
+     sprintf("%5s", as.character(.col))
+ })
>
> str(newTemp)
'data.frame':   5 obs. of  3 variables:
 $ DX1: chr  "13761" "63371" "51745" "64081" ...
 $ DX2: chr  " 8125" "  v75" "77703" "32826" ...
 $ DX3: chr  "49178" "22237" "93500" "  v72" ...
>


On Tue, Aug 10, 2010 at 2:55 PM, GL <pflugg at shands.ufl.edu> wrote:
>
> Using the input below, can I do something more elegant (and more efficient)
> than the loop also listed below to pad strings to a width of 5? The true
> matrix is about 300K rows and 31 columns.
>
> #######################
> #INPUT
> #######################
>> temp
>    DX1   DX2   DX3
> 1 13761  8125 49178
> 2 63371   v75 22237
> 3 51745 77703 93500
> 4 64081 32826   v72
> 5 78477 43828 87645
>>
>
> #######################
> #CODE
> #######################
>
> ssize <- c(nrow(temp), ncol(temp))
> aa <- c(1:ssize[2])
> aa <- paste("DX", aa, sep = "")
> record <- matrix("?", nrow = ssize, ncol = ssize[2])
> colnames(record) <- aa
>
> mm <- 0
>    #for (j in 1:1) {
>    for (j in 1:ssize[1]) {
>        mm <- j
>        a <- as.character(as.matrix(as.data.frame(temp[j,])))
>        len2 <- sum(a != "?")
>        mi <- 0
>        for (k in 1:len2) {
>            aa <- a[k]
>            a0 <- 5 - nchar(aa)
>            if (a0 > 0) {
>                for (st in 1:a0) {
>                  aa <- paste(aa, " ", sep = "")
>                }
>            }
>            record[j, k] <- aa
>        }
>    }
>
> #######################
> #OUTPUT
> #######################
>
>    DX1   DX2   DX3
> 1 13761  8125 49178
> 2 63371   v75 22237
> 3 51745 77703 93500
> 4 64081 32826   v72
> 5 78477 43828 87645
> --
> View this message in context: http://r.789695.n4.nabble.com/sapply-lapply-instead-of-loop-tp2320265p2320265.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list