coderX
coderX

Reputation: 474

Is there a simple way to add dollar signs to a column?

Is there a simple way to add dollar signs to a column that I have? I can't find any way within format() other than just decimals, commas, etc.. For example, I have:

numbers <- data.frame(x1 = 1:4, x5 = 11:14, x6 = 21:24, y = 31:34)

How can I format numbers$y to have dollar signs in front of it?

Upvotes: 1

Views: 9124

Answers (4)

uribo
uribo

Reputation: 37

I like {tidyr} for its ease of use:

data.frame(x1 = 1:4, x5 = 11:14, x6 = 21:24, y = 31:34, unit = "$") %>% 
  tidyr::unite_("y2", c("unit", "y"), sep = "", remove = TRUE)

Upvotes: 0

Rich Scriven
Rich Scriven

Reputation: 99331

If you wanted to go supreme overkill and keep the numerics on the column, but have them print with a dollar sign, you could write a print method.

class(numbers$y) <- "dollar"
format.dollar <- function(x, ...) paste0("$", unclass(x))
as.data.frame.dollar <- base:::as.data.frame.factor

Now it prints with the dollar signs ...

numbers
#   x1 x5 x6   y
# 1  1 11 21 $31
# 2  2 12 22 $32
# 3  3 13 23 $33
# 4  4 14 24 $34

... but the column is still numeric.

numbers$y[]
# [1] 31 32 33 34

Upvotes: 5

DrewMcD
DrewMcD

Reputation: 41

Try this:

numbers$y <- paste0('$', numbers$y)

Note that you should only do this once you're done processing this column -- after you add the dollar sign it will be a chr and not eligible for numerical computations.

To undo this step, you can use:

as.numeric(substring(text = numbers$y, first = 2))

For future reference, paste0(...) is simply a shortcut for paste(..., sep=""). Since paste defaults to a space separation.

Upvotes: 1

Steve
Steve

Reputation: 43

numbers$y<-paste("$",numbers$y)

Will do it nicely. But beware, it is then treated as text and not a number

Upvotes: 2

Related Questions