简体   繁体   中英

Add “%” to a dataframe of column percentages in R

I have a dataframe of percentages. I want to add a "%" at the end of each cell so that I can export/display them properly. It looks something like

    c1   c2
r1  2.1  3.5
r2  3.4  4.5

I would like to have:

    c1    c2
r1  2.1%  3.5%
r2  3.4%  4.5%

I don't really need the output to be a dataframe specifically, just something that would preserve the column and row names.

For more control of the format, consider sprintf() with the %% formatting option:

# One more column of values
  df <- as.data.frame(rbind(c(2.1, 3.5, 2), c(3.4, 4.5, 1/3)))
  dimnames(df) <- list(paste0("c", 1:2), paste0("r", 1:3))

# Compare these two approaches:
  as.data.frame(lapply(df, paste0, "%"))
  as.data.frame(lapply(df, function(x) sprintf("%3.1f%%", x)))

Most straightforward approach is probably,

df[] <- paste0(as.matrix(dataframe), "%")

We could also use apply ,

df[] <- apply(df, 1, function(x) paste0(x, "%"))

An alternative is to use the mutate_all from dplyr,

library(dplyr)
dataframe %>% 
     mutate_all(list(~paste0(., "%")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM