r - pad numeric column with leading zeros -
i've been looking past few hours. have tried using sprintf
changes column character. want have fixed-width numeric column, padded zeros.
if you're willing use custom class, can write print method this. make data frame, , give custom class:
df <- data.frame(a=letters[1:10], b=sample(c(1, 10, 100), 10, rep=t), c=sample(c(1, 10, 100), 10, rep=t)) class(df) <- c("my_df", class(df))
write print method uses @benbolker's formatting:
print.my_df <- function(x, ...) { num.cols <- sapply(x, is.numeric) x[num.cols] <- lapply(x[num.cols], sprintf, fmt="%04d") nextmethod() }
and then:
df
produces:
b c 1 0100 0100 2 b 0010 0001 3 c 0001 0010 4 d 0001 0100 5 e 0001 0001 6 f 0001 0001 7 g 0001 0001 8 h 0001 0100 9 0001 0100 10 j 0001 0001
you can still use data frame same way since numbers converted when printed.
> sum(df$b) [1] 118
Comments
Post a Comment