Reputation: 87
I have read a number of ways to show more digits in R output (to R Studio display) but the methods I have reviewed do not work for a tsibble with a mixture of character and numeric columns. I am able to use the num() function to set the number of digits for an individual numeric column but I would like to show the full tsibble object with character columns intact.
In the example below, I would like the output to be the same as that shown except the x1 and x2 columns should have three digits after the decimal for all rows.
Thank you in advance for your help.
library(tidyverse)
library(tsibble)
data <- tibble(date = seq(as.Date("2022/1/1"), by = "month", length.out = 6),
region = c("A","C","A","B","C","C"),
x1 = c(7.3456, 123.4532, 106.1059, 17.1594, 175.3951, 62.9431),
x2 = c(12.12, 15.29, 27.92, 9.23, 16.29, 13.11))
data <- data %>%
mutate(month = yearmonth(date)) %>%
as_tsibble(index = month)
data
data
# A tsibble: 6 x 5 [1M]
date region x1 x2 month
<date> <chr> <dbl> <dbl> <mth>
1 2022-01-01 A 7.35 12.1 2022 Jan
2 2022-02-01 C 123. 15.3 2022 Feb
3 2022-03-01 A 106. 27.9 2022 Mar
4 2022-04-01 B 17.2 9.23 2022 Apr
5 2022-05-01 C 175. 16.3 2022 May
6 2022-06-01 C 62.9 13.1 2022 Jun
>
Upvotes: 2
Views: 82
Reputation: 23598
As Jon Spring mentioned in the comments mutate(across(where(is.numeric), ~num(.,digits = 3)))
does work, the same as it does for tibbles, section Fixed number of digits.
Do note the the print under x1 and x2. It will show num:.3! instead of . But this is just a print from how tibbles are printed. The data in x1 and x2 is still a double.
In your code:
data %>%
mutate(month = yearmonth(date),
across(where(is.numeric), ~num(.,digits = 3))) %>%
as_tsibble(index = month)
# A tsibble: 6 x 5 [1M]
date region x1 x2 month
<date> <chr> <num:.3!> <num:.3!> <mth>
1 2022-01-01 A 7.346 12.120 2022 Jan
2 2022-02-01 C 123.453 15.290 2022 Feb
3 2022-03-01 A 106.106 27.920 2022 Mar
4 2022-04-01 B 17.159 9.230 2022 Apr
5 2022-05-01 C 175.395 16.290 2022 May
6 2022-06-01 C 62.943 13.110 2022 Jun
Upvotes: 1