I have a data.frame that contains numbers and strings and I'd like to control digits in an xtable print. For some reason, xtable seems to ignore the digits=2
command. See:
\documentclass{article}
\begin{document}
<<echo=F, results='asis'>>=
library("xtable")
df <- data.frame(matrix( c("aaa", "bbb", seq(0.1, 1, length.out=6) ), 2, 4) )
print(xtable(df, digits=2))
print(xtable(df, digits=c(0, 0, 2, 2, 2)))
@
\end{document}
None of the two prints does affect number of digits in the output, i.e. both supress zeros behind the comma, e.g. 0.1 and 1. I'd like it to be 0.10 and 1.00 respectively so that all numbers have same lengths.
digits=2
command perfectly works though when there are no strings in the data.frame. See:
df2 <- data.frame(matrix( seq(0.1, 1, length.out=6), 2, 3) )
print(xtable(df2, digits=2))
What I am looking for is a way to print a data.frame in xtable that does include strings with digits of all numerical values to be 2.
Does anyone know a solution?
In your example, you create your data frame from a character matrix, each column of which is a character. Xtable doesn't know how to apply digits to a character. Try defining your data.frame as a data.frame from the beginning, then numeric columns will be numeric, and character columns will be character. This should work:
df <- data.frame(X1 = c("aaa", "bbb"),X2 = c(0.1,0.28),X3 = c(0.46,0.64), X4 = c(0.82, 1))
print(xtable(df, digits=2))
And as requested, a quick way to convert all-character data frame into a mix of character and numeric columns:
df[] <- lapply(df, function(x) if (anyNA(y <- as.numeric(x))) x else y)
And another, a little bit more elegant solution in data.table
package:
library(data.table)
setDT(df)[, lapply(.SD, function(x) if(anyNA(y <- as.numeric(x))) x else y)]