3

When I run the following line by line in R it works fine, but with knitr the options(digits=3) gets ignored.

Why? Any solutions?

<<cor>>=
#mock up data set.
x <- c(rnorm(100))
y <- c(rnorm(100))
z <- c(rnorm(100))
df <- as.data.frame(cbind(x,y,z))
df$x<- as.numeric(df$x)
df$y<- as.numeric(df$y)
df$z<- as.numeric(df$z)
options(digits=3)
cor(df, use = 'na.or.complete', method = c("spearman"))
@
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Gerit
  • 195
  • 2
  • 14
  • Did you try running that code in just a clean R session? I get the same result whether I run in knitr or just directly. (make sure to add a call to `set.seed` in there to make sure you get the same output) – Dason Nov 19 '12 at 19:57
  • 1
    Note that my comment essentially boils down to - "knitr doesn't ignore the options - your expectation for what happens in that code just seems to be wrong" – Dason Nov 19 '12 at 20:01
  • @Dason I don't know whether I understood correctly. However, in this case I don't worry about the reproducibility. My issue is that I cannot reduce the digits down to three only (and not seven). – Gerit Nov 19 '12 at 22:28
  • I was asking if you run that code in a normal R session (instead of knitr) you should get the same thing. This isn't a knitr issue as much as it is an issue of how the digits get handled. For example if you change it to `options(digits=22)` you should see a big difference in the number of digits that get printed. – Dason Nov 19 '12 at 22:34
  • Now I understood. Yes, actually, in both cases I have more than three digits. See below. – Gerit Nov 20 '12 at 13:49

1 Answers1

2

I found a solution while searching for a different issue. Leave out options(digits=3) and use

round(cor(df, use = "na.or.complete", method = c("spearman")), digits = 3)

Which leaves the question why the options(...) doesn't work. But I can happily live with that!

Thanks everyone for their time!

Gerit

Gerit
  • 195
  • 2
  • 14
  • From `?options`: ‘digits’: controls the number of digits to print when printing numeric values. It is a suggestion only. Valid values are 1...22 with default 7. See the note in ‘print.default’ about values greater than 15. – Dason Nov 20 '12 at 00:56
  • "It is a suggestion only." Does that mean it is not a strict measure and hence `option(digits=i)` is only a rough approximation of how many digits result? I would find that odd for such a cool program like R, but with `round(..., digits=i)` I can well work around it. Can you tell I am not a programmer by heart?! Thank you for caring. – Gerit Nov 20 '12 at 13:52
  • for the meaning of _suggestion only_, I guess you need to ask either R core or someone who understands `./src/main/print.c` in R source; my superficial understanding is only that it may not give you the expected number of digits precisely; for precise control, you need functions like `round()` or `formatC()` – Yihui Xie Nov 20 '12 at 19:39