zengc
zengc

Reputation: 97

How to print a DT with different digits for columns?

In the toy example below, how can I print the data.table with different digits for V1, V2 and V3.

rm(list=ls())
set.seed(2020)
library(data.table)
 
x <- data.table(matrix(rnorm(10*3), 10))
print(x, digits=2)
       V1     V2     V3
 1:  0.38 -0.853  2.174
 2:  0.30  0.909  1.098
 3: -1.10  1.196  0.318
 4: -1.13 -0.372 -0.073
 5: -2.80 -0.123  0.834
 6:  0.72  1.800  0.199
 7:  0.94  1.704  1.298
 8: -0.23 -3.039  0.937
 9:  1.76 -2.289 -0.147
10:  0.12  0.058  0.110

Upvotes: 0

Views: 90

Answers (2)

zengc
zengc

Reputation: 97

Motivated by Ronak, the below solution works.

rm(list=ls())
set.seed(2020)
library(data.table)
x <- data.table(matrix(rnorm(10*3), 10))
digits <- 2:4
x[, mapply(round, .SD, digits)]

         V1     V2      V3
 [1,]  0.38 -0.853  2.1744
 [2,]  0.30  0.909  1.0982
 [3,] -1.10  1.196  0.3182
 [4,] -1.13 -0.372 -0.0731
 [5,] -2.80 -0.123  0.8343
 [6,]  0.72  1.800  0.1988
 [7,]  0.94  1.704  1.2978
 [8,] -0.23 -3.039  0.9367
 [9,]  1.76 -2.289 -0.1474
[10,]  0.12  0.058  0.1104

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389135

Not sure if it is possible to do this keeping the data as numeric but here is a trick using regular expressions.

set.seed(2020)
library(data.table)
x <- data.table(matrix(rnorm(10*3), 10))
digits <- c(2, 3, 4)

x[, Map(function(x, y) sub(sprintf('(.*\\..{%s}).*', y), '\\1', x), .SD, digits)]

#       V1     V2      V3
# 1:  0.37 -0.853  2.1743
# 2:  0.30  0.909  1.0981
# 3: -1.09  1.196  0.3182
# 4: -1.13 -0.371 -0.0731
# 5: -2.79 -0.123  0.8342
# 6:  0.72  1.800  0.1987
# 7:  0.93  1.703  1.2978
# 8: -0.22 -3.038  0.9367
# 9:  1.75 -2.288 -0.1474
#10:  0.11  0.058  0.1104

Using sprintf we create a pattern to extract different number of digits as defined in digits for each column. For example, for 1st value in digits i.e 2 the pattern would become

sprintf('(.*\\..{%s}).*', y)
#[1] "(.*\\..{2}).*"

meaning extract everything until a "." and 2 characters after it. Similarly we do this for other columns.

Upvotes: 1

Related Questions