r - Pretty printing zeros in data.frame with integers and doubles to CSV -


i have following data.frame:

q <- data.frame(a = rep(0,12), b = rep(c(0,1),6), c = 0:11, d = c(rep(0.0,10),0.003579535,0.045418328), e = c(rep(0.0,10),0.001716128,0.057440227))  > q    b  c           d           e 1  0 0  0 0.000000000 0.000000000 2  0 1  1 0.000000000 0.000000000 3  0 0  2 0.000000000 0.000000000 4  0 1  3 0.000000000 0.000000000 5  0 0  4 0.000000000 0.000000000 6  0 1  5 0.000000000 0.000000000 7  0 0  6 0.000000000 0.000000000 8  0 1  7 0.000000000 0.000000000 9  0 0  8 0.000000000 0.000000000 10 0 1  9 0.000000000 0.000000000 11 0 0 10 0.003579535 0.001716128 12 0 1 11 0.045418328 0.057440227 

i save in csv following format:

"a","b","c","d","e" 0,0,0,0.000000000,0.000000000 0,1,1,0.000000000,0.000000000 0,0,2,0.000000000,0.000000000 0,1,3,0.000000000,0.000000000 0,0,4,0.000000000,0.000000000 0,1,5,0.000000000,0.000000000 0,0,6,0.000000000,0.000000000 0,1,7,0.000000000,0.000000000 0,0,8,0.000000000,0.000000000 0,1,9,0.000000000,0.000000000 0,0,10,0.003579535,0.001716128 0,1,11,0.045418328,0.057440227 

how can in format? i'm not sure how use existing functionality in print,format, , formatc before calling write.csv. first 3 columns should printed integers , last 2 columns should printed doubles 9 decimal places, including zeros.

?write.csv explains how this:

in cases conversion of numeric quantities governed option "scipen" (see options), internal equivalent of digits = 15. finer control, use format make character matrix/data frame, , call write.table on that.

indeed, default arguments format sufficient needs:

write.csv(format(q),row.names=false) "a","b","c","d","e" "0","0","0","0.000000000","0.000000000" "0","1","1","0.000000000","0.000000000" "0","0","2","0.003579535","0.001716128" "0","1","3","0.045418328","0.057440227" 

due various conventions want apply data, think have header , data separately:

# write header write.csv(q[0,],"mydata.csv",row.names=false) # "a","b","c","d","e"  # add data write.table(format(q,trim=true),"mydata.csv",row.names=false,col.names=false,sep=",",quote=false,append=true) # 0,0,0,0.000000000,0.000000000 # 0,1,1,0.000000000,0.000000000 # 0,0,2,0.000000000,0.000000000 # 0,1,3,0.000000000,0.000000000 # 0,0,4,0.000000000,0.000000000 # 0,1,5,0.000000000,0.000000000 # 0,0,6,0.000000000,0.000000000 # 0,1,7,0.000000000,0.000000000 # 0,0,8,0.000000000,0.000000000 # 0,1,9,0.000000000,0.000000000 # 0,0,10,0.003579535,0.001716128 # 0,1,11,0.045418328,0.057440227 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -