Reputation: 29
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.
Upvotes: 2
Views: 1692
Reputation: 259
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(., "%")))
Upvotes: 1
Reputation: 803
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)))
Upvotes: 2