Print out matrix in R within function for which each column has a specified number of digits defined by a function parameter

StackOverflow https://stackoverflow.com/questions/20453100

  •  30-08-2022
  •  | 
  •  

Question

I have been thinking about this for some time already but I cannot find the solution. Here is the problem. I have a function that iteratively calculated the root for a function that I plug in there. So for every iteration I come closer to the final solution (Newton procedure). Within the function I build a matrix that stores the number of the iteration (i), the value for x (x) and the value for f(x) (y).

matrix <- rbind(matrix, c(i,x,y))

The function itself works perfectly fine. But I want to print out the result in a specific way. I want to return the matrix that is built in the function like this:

       [,1]      [,2]          [,3]             
  [1,] "1"   "0.000"       "3.000"              
  [2,] "2"   "-299999.975" "89999985109.735"
  [3,] "3"   "-150000.381" "22500114442.253"
  [4,] "4"   "-75000.123"  "5625014307.234"     
  [5,] "5"   "-37500.048"  "1406253577.781" 
  [6,] "6"   "-18750.030"  "351563619.088"  
  [7,] "7"   "-9375.093"   "87890906.234"       
  [8,] "8"   "-4687.507"   "21972727.599"   
  [9,] "9"   "-2343.753"   "5493182.588"

What I am doing at the moment is:

return(matrix(sprintf(c("%.0f","%.3f","%.3f"),matrix),nrow=N))

But this yields

    [,1]      [,2]          [,3]             
  [1,] "1"       "0"           "3"              
  [2,] "2.000"   "-299999.975" "89999985109.735"
  [3,] "3.000"   "-150000.381" "22500114442.253"
  [4,] "4"       "-75000"      "5625014307"     
  [5,] "5.000"   "-37500.048"  "1406253577.781" 
  [6,] "6.000"   "-18750.030"  "351563619.088"  
  [7,] "7"       "-9375"       "87890906"       
  [8,] "8.000"   "-4687.507"   "21972727.599"   
  [9,] "9.000"   "-2343.753"   "5493182.588"   

So the digits are somehow specified by column and not by row. In a next step - to make it even more complicated - my function is supposed to have a parameter that allows users to specify the number of digits of column 2 and 3. so something like:

newton <- function(fx, p=0)

Where p is the number of digits and by default 0.

Can somebody help me with this? Thank you!

Was it helpful?

Solution

If your matrix has always 3 columns you can simply do:

x.digits = 3
y.digits = 4

mxStr <- 
cbind(sprintf('%d',mx[,1]),
      sprintf(paste('%.',x.digits,'f',sep=''),mx[,2]),
      sprintf(paste('%.',y.digits,'f',sep=''),mx[,3])
      )

Of course you can wrap this code in a function and pass x.digits and y.digits as parameters...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top