Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including % or any other sign next to numerical value in data.frame R

Tags:

r

I would like to include sign % in a data.frame so that the data.frame is later printed as print(xtable(data.frame....)) with a % sign right next to the numerical values of data2in every row of a column Values in %.

Data example:

data1 <- rnorm(5,10,2)
data2 <- round(rexp(5,2),1)
frameData <- data.frame(data1,data2)
colnames(frameData) <- c("Measurement","Values in %")

I have tried something like this:

data1 <- rnorm(5,10,2)
data2 <- round(rexp(5,2),1)
data3 <- rep("%",5)
frameData <- data.frame(data1,data2,data3)
colnames(frameData) <- c("Measurement","Values in %","")

But I can not get the sign close enough and later print(xtable(frameData....)) the distance magnifies.

like image 415
Maximilian Avatar asked Dec 21 '25 05:12

Maximilian


1 Answers

@AnandaMahto has given a great answer using base R.

There's an easier way if you're willing to use a library though. The scales library has a bunch of functions for formatting numbers:

library(scales)
> percent(seq(10)/10)
 [1] "10%"  "20%"  "30%"  "40%"  "50%"  "60%"  "70%"  "80%"  "90%"  "100%"

Finally, because numeric types can't hold % values, you could add an attribute to the data.frame, then later use this when printing:

attr(frameData,"pctCols") <- c(2)
printPct <- function(x) { require(taRifx); japply(x,attr(x,"pctCols"),percent) }
> printPct(frameData)
  Measurement Values in %
1   11.992833        160%
2   12.556494        NaN%
3   10.837724        200%
4    9.141887        200%
5    8.056046        100%
like image 160
Ari B. Friedman Avatar answered Dec 24 '25 00:12

Ari B. Friedman