I must be missing something. There must be a way to have write_csv
only export a column with 2 decimal points. For my use case, I could work with excel or csv or anything. But I need a file exported with two decimal points and it should be easy code.
var1<-sample(c("A","B"), size=10, replace=T)
var2<-rnorm(10, mean=5, sd=1)
var2
df<-data.frame(var1, var2)
library(readr)
#Try with xtable
library(xtable)
xtable(df, digits=2) %>%
write_csv(., file="test.csv")
You can round the values to limit precision
df |>
dplyr::mutate(var2=round(var2, 2)) |>
readr::write_csv(file="test.csv")
But that will still use default rules for printing decimal values. If you need an exact formatted string, you should use a function like format
or sprintf
to format your numbers exactly how you want.