简体   繁体   中英

R - Coerce list objects using percent (formattable)

I want to use percent from formattable package to coerce a dataset to percent form. The virgin dataset looks like below:

C1 C2  C3  C4
a  .01 .03 .3
b  .3  .5  .7

Expected result (ignoring decimals):

C1 C2  C3  C4
a  1%  3%  30%
b  30% 50% 70%

Now, I tried (number of columns might vary, but only C1 will have characters):

DF[, c(2:ncol(DF))] <- percent(DF[, c(2:ncol(DF))])

Showing error:

Error in as_numeric(x) : (list) object cannot be coerced to type 'double'

Now, When I tried it column wise, using a loop ( percent(DF[, i]) ), it worked smoothly as expected. It seems that percent cannot coerce 2D data at once. However, I want to know if there is a way to avoid the loop and come up with a beautiful solution.

Thanks in advance.

For these kind of tasks I really like dplyr::mutate_if :

library(dplyr)
library(formattable)
DF %>% mutate_if(is.numeric, percent)

If not all of them should be transformed to % (because not a value between 0 and 1 for example), you could extend it to:

DF %>% mutate_if(function(x){all(between(x, 0, 1))}, percent)

We need to loop through the columns

library(formattable)
df1[-1] <- lapply(df1[-1], percent)

This can be done with base R

df1[-1] <- lapply(df1[-1], function(x) paste0(x *100, "%"))

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