How to retain only one space between columns in dataframe

I want to output the dataframe as a table with no extension name, but I have problems with it. I found that after removing scientific notation, there are fixed spaces between each column. For example, there may be more than one space for some rows between 4th and 5th columns. However, I want to keep only one space between the columns, rather than fixed locations. Could anyone help me with this problem?
The data and the code are shown below. Thanks.

create a small sample

df= data.frame(V1=10:25,
V2=c(rep(35.25,8),rep(35.75,8)),
V3=c(rep(c(120.25,120.75,121.25,121.75,122.25,122.75,123.25,123.75),2)),
V4=c(0.0001,0.002,0.0005,0.0003,0.0002,0.0002,0.0002,0.0002,0.0002,0.0002,
0.0004,0.04,0.0004,0.03,0.05,0.6),
V5=c(10.1,11.2,9.5,8.2,11.5,20.2,2.1,25.1,24,10.8,10.9,16.5,18.3,12,20.3,22.4))

keep four decimal places in columns V2 and V3

df[,2:3] = format(df[,2:3],nsmall=4)

remove scientific notation

df = format(df, scientific=F)

write the output

write.table(df,'~/directorypath/samp',row.names=F,col.names=F,quote=F)

What you are seeing is a result of your last format() command. Try this line instead.

df = format(df, scientific=F, trim = TRUE)
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.