Maximilian
Maximilian

Reputation: 4229

Including % or any other sign next to numerical value in data.frame 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.

Upvotes: 3

Views: 107

Answers (2)

Ari B. Friedman
Ari B. Friedman

Reputation: 72769

@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%

Upvotes: 5

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193647

I would probably just suggest using sprintf, which would give you pretty good control over formatting things like this.

Here's a basic example:

frameData$`Values in %` <- sprintf("%1.1f%%", frameData$`Values in %`)
frameData
#   Measurement Values in %
# 1   13.423642        0.2%
# 2   12.464654        0.2%
# 3   10.805657        0.2%
# 4   11.188839        1.6%
# 5    9.248013        0.2%

Upvotes: 4

Related Questions