Skip to content
Prev 310294 / 398506 Next

Formatting digits in a table with mix of numbers and characters

On Nov 8, 2012, at 10:14 AM, Brian Hobbs <brhobbs at gmail.com> wrote:

            
Some things to note:

1. First, note that 'table' is coerced to a character matrix, since a matrix can only hold one data type. So, even though you included numeric values in the creation, they were coerced to character in the resultant object.

2. I would not be concerned with whether xtable gets a numeric or character based object. You are outputting to LaTeX, which is all going to be character based anyway. I would focus on getting the data into a format that you want and then simply use xtable() to generate the LaTeX markup.

3. Although R is typically smart enough to differentiate between an object named 'table' and the built-in function table(), I would avoid it, because there may be times when you will run into a problem and be scratching your head as to the source of the error.


Vec <- c(12.34567, "--", 10, 12.34567, "--", "NA", "--", 123.45678,  "--")

# Warnings about NA's will occur here
Vec.new <- ifelse(!is.na(as.numeric(Vec)), signif(as.numeric(Vec), 4), Vec)
[1] "12.35" "--"    "10"    "12.35" "--"    "NA"    "--"    "123.5"
[9] "--"
[,1]    [,2]    [,3]
[1,] "12.35" "--"    "10"
[2,] "12.35" "--"    "NA"
[3,] "--"    "123.5" "--"


Regards,

Marc Schwartz