[R] sapply/lapply instead of loop
GL
pflugg at shands.ufl.edu
Tue Aug 10 20:55:16 CEST 2010
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.
More information about the R-help
mailing list