0

I'm working mainly off of this post to conditionally format some numbers I have in two columns. Here's a dataframe:

d <- data.frame(ID = c("a","b","c"), 
                total = c(145000000, 9.5, 867455), 
                se = c(9000000,0.84,120835),stringsAsFactors=FALSE)

I'm trying to apply the suffix "M" for numbers above 100,000 but leave smaller numbers alone for this formatting.

From that earlier post, I've tried to adapt the solution like so:

d[,2:3] <- ifelse(d[,2:3] > 100000, paste(round(d[,2:3] / 1e6, 1), trim = TRUE), "M")

But either nothing happens when I run the code (d remains unchanged) or I get this error: non-numeric argument to binary operator

For reference, I'd like the dataframe to look like this:

d <- data.frame(ID = c("a","b","c"), 
                total = c("1.45M", 9.5, "0.867M"), 
                se = c("9.0M",0.84,"0.12M"),stringsAsFactors=FALSE)

I don't mind if the results are character-formatted, as this is going to be output to a table in LaTeX and I won't be doing operations on these numbers.

Thanks!

logjammin
  • 1,121
  • 6
  • 21

1 Answers1

0

This function will convert a numeric value to that format, then just use sapply to apply it to each column of the data.frame

milfun <- function(x) {ifelse(x>1e5,paste0(round(x/1e6,3),"M"),x)}
d$total <- sapply(d$total,milfun)
d$se <- sapply(d$se,milfun)
d
  ID  total     se
1  a   145M     9M
2  b    9.5   0.84
3  c 0.867M 0.121M

note you had 145000000=145M, not 1.45M in your desired response.