Format model display in texreg or stargazer R as scientific

后端 未结 3 950
感动是毒
感动是毒 2021-02-08 18:59

I just ran a statisitical model and i want it to display the results of the model as a table using stargazer. However, the large numbers are displayed in full.

         


        
3条回答
  •  北海茫月
    2021-02-08 19:40

    To do this, you can write your own function to take the large numbers and put them into scientific notation.

    First, load the stargazer package:

    library(stargazer)
    

    Then, create data with large numbers for the example:

    set.seed(1)
    
    C <- data.frame("A" = rnorm(10000, 30000, 10000),
                    "B" = rnorm(10000, 7500, 2500))
    

    Fit the model and store the stargazer results table in an object:

    fit2 <- lm(A ~ B, data = C) 
    
    myResults <- stargazer(fit2, type = "text")
    

    Create a function to take a stargazer table and convert large numbers into scientific notation. (This is not very flexible but can be with simple modifications. Right now only works for 1,000 - 99,999)

    fixNumbers <- function(stargazer.object){
    
      so <- stargazer.object
      rows <- grep(".*[\\d+],[\\d+].*", so, perl = T)
      for(row in rows){
    
        # Get number and format into scientific notation
        number <- as.numeric(sub(".*([0-9]{1,2}),([0-9]+\\.?[0-9]*).*", "\\1\\2", so[row], perl = T))
        formatted_num <- sprintf("%.2e", number)
        so[row] <- sub("(.*)[0-9]{1,2},[0-9]+\\.?[0-9]*(.*)", paste0("\\1", formatted_num, "\\2"), so[row], perl = T)
      }
    
      # Print result
      for(i in 1:length(so)){
        cat(so[i], "\n")
      }
    }
    

    Give the new function (fixNumbers) your stargazer object:

    fixNumbers(myResults)
    

    -- Here's all the code in one chunk: --

    library(stargazer)
    
    set.seed(1)
    
    C <- data.frame("A" = rnorm(10000, 30000, 10000),
                    "B" = rnorm(10000, 7500, 2500))
    
    fit2 <- lm(A ~ B, data = C) 
    
    myResults <- stargazer(fit2, type = "text")
    
    fixNumbers <- function(stargazer.object){
    
      so <- stargazer.object
      rows <- grep(".*[\\d+],[\\d+].*", so, perl = T)
      for(row in rows){
    
        # Get number and format into scientific notation
        number <- as.numeric(sub(".*([0-9]{1,2}),([0-9]+\\.?[0-9]*).*", "\\1\\2", so[row], perl = T))
        formatted_num <- sprintf("%.2e", number)
        so[row] <- sub("(.*)[0-9]{1,2},[0-9]+\\.?[0-9]*(.*)", paste0("\\1", formatted_num, "\\2"), so[row], perl = T)
      }
    
      # Print result
      for(i in 1:length(so)){
        cat(so[i], "\n")
      }
    }
    
    fixNumbers(myResults)
    

提交回复
热议问题