[英]R - Coerce list objects using percent (formattable)
I want to use percent
from formattable
package to coerce a dataset to percent form. 我想用
percent
从formattable
包强迫一个数据集%的形式。 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): 现在,我尝试了一下(列数可能会有所不同,但只有C1会包含字符):
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. 现在,当我使用循环(
percent(DF[, i])
)以列方式对其进行尝试时,它可以按预期顺利运行。 It seems that percent cannot coerce 2D data at once. 似乎百分比无法一次强制转换2D数据。 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
: 对于这些任务,我真的很喜欢
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: 如果不是所有值都应转换为%(例如,因为值不介于0和1之间),则可以将其扩展为:
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
这可以用
base R
完成
df1[-1] <- lapply(df1[-1], function(x) paste0(x *100, "%"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.