Limiting the number of decimals in a dataframe (R)

后端 未结 4 1833
青春惊慌失措
青春惊慌失措 2021-02-05 08:26

I would like to limit the number of decimals when a data frame is imported. My .txt input have 16 decimals to each row in collumn \"Value\". My dataframe look like that:

4条回答
  •  孤城傲影
    2021-02-05 09:14

    just throw a copy of this into the path of your project in a utils directory and source it when you run your script

    "formatColumns" <-
     function(data, digits)
     {
        "%,%" <- function(x,y)paste(x,y,sep="")
        nms <- names(data)
        nc <- ncol(data)
        nd <- length(digits)
        if(nc!=nd) 
          stop("Argument 'digits' must be vector of length " %,% 
               nc %,% ", the number of columns in 'data'.")
        out <- as.data.frame(sapply(1:nc, 
                             FUN=function(x, d, Y)
                             format(Y[,x], digits=d[x]), Y=tbl, d=digits))
        if(!is.null(nms)) names(out) <- nms
        out
    }
    

    Now you can sit back and relax

    formatColumns(MyData, digits=c(0,2,4,4,4,0,0))
    

    et cetera et cetera et cetera

提交回复
热议问题