Is it possible to control the number of digits for display on a table?

7,403 views
Skip to first unread message

shenglan zhang

unread,
Mar 31, 2013, 9:08:06 PM3/31/13
to shiny-...@googlegroups.com
Hi,
So in RStudio, you can set the digits to display in the session by using options(digits = 4). But in Shiny, how do you get to control the number of digits that is to be displayed? There is an option to print a dataframe object for a specific # of digits. But how can I do that in the server.R renderTable?

Thanks for your help!

ricardo andres burgos ocampo

unread,
Apr 1, 2013, 12:44:16 AM4/1/13
to shiny-...@googlegroups.com
I think in two form to solution, but you can find a lot of it, the first is use R to cut the digits.
the source is like a:
 
table <-renderTable({
  mat = matrix(nrow=10,ncol=10)
  for(i in 1:length(mat)){
    mat[i,3] = sprint("%.4f",mat[i,3])
  }
  return(mat)
  })

here, you are save in each cell of the column the number but with less digits.

The second form is used a css to control the width of your cell, why use this?, I think that when you have a big matrix with a lot of process, the server will be run slow, so if you use graph part, the process is made for a client and you can control more the work of your server.

css style.

table tbody tr td:last-child{
   width: 20px;

Winston Chang

unread,
Apr 1, 2013, 11:22:17 AM4/1/13
to shiny-...@googlegroups.com
renderTable passes any extra arguments along to xtable, so I think you should be able to do something like this:

renderTable({
   # Code to generate table here
}, digits=4)


It looks like xtable only lets you control the total number of digits, and not the number of digits after the decimal point. If you need finer control, you can use sprintf() to convert it to a string with a specified format. In this example, it converts column x to a string with 3 digits after the decimal point:

df <- data.frame(x=rnorm(10), y=rnorm(10), label=letters[1:10])
df$x <- sprintf('%1.3f', df$x)


If you want to do this to all columns in the data frame, you could do something like this:

# Given a column: if numeric, convert to formatted string; otherwise, return unchanged
format_num <- function(col) {
  if (is.numeric(col))
    sprintf('%1.3f', col)
  else
    col
}

# Apply the function to each column, and convert the list output back to a data frame
as.data.frame(lapply(df, format_num))


-Winston


--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages