我想将它们转换为整数,然后转换为百分比。 例如,将0.318转换为32分,然后创建一个显示“ 32%”的列,或显示百分比标记(即0-9、10-19 ... 90-99
)的列> exam_results_stats <-
tibble(exam_one = runif(1:10), exam_two = runif(1:10), exam_three =
runif(1:10), exam_four = runif(1:10), exam_five = runif(1:10),
exam_six = runif(1:10))
exam_results_stats[, 1:6]
exam_one exam_two exam_three exam_four
<dbl> <dbl> <dbl> <dbl>
1 0.318 0.225 0.432 0.915
2 0.0747 0.0854 0.217 0.879
3 0.327 0.188 0.211 0.582
4 0.260 0.593 0.754 0.427
5 0.0569 0.172 0.519 0.258
6 0.175 0.721 0.395 0.740
7 0.0530 0.414 0.924 0.919
8 0.486 0.670 0.491 0.894
9 0.566 0.891 0.786 0.868
10 0.466 0.762 0.0480 0.0377
答案 0 :(得分:1)
首先,您可以使用paste0
和round
编写函数。将其包装在format
中会很有帮助,这样始终会显示正确的小数位数。然后,您可以使用lapply
将此功能应用于所有列。
fxn <- function(x) {
format(paste0(round(x * 100, 0), "%"), nsmall = 2)
}
exam_results_stats[1:6] <- lapply(exam_results_stats[1:6], fxn)
答案 1 :(得分:0)
使用tidyverse
和一些基数R
exam_results_stats <- tibble(
exam_one = runif(1:10), exam_two = runif(1:10),
exam_three = runif(1:10), exam_four = runif(1:10),
exam_five = runif(1:10), exam_six = runif(1:10))
exam_results_stats %>%
mutate_all(function(x) paste0(as.character(round(x*100, digits= 0)),"%"))
# A tibble: 10 x 6
exam_one exam_two exam_three exam_four exam_five exam_six
<chr> <chr> <chr> <chr> <chr> <chr>
1 87% 34% 61% 58% 65% 96%
2 49% 84% 18% 26% 92% 48%
3 28% 33% 16% 74% 4% 5%
4 2% 43% 16% 21% 98% 95%
5 4% 30% 16% 97% 57% 58%
6 1% 23% 21% 20% 31% 37%
注意:您的数据现在是非数字数据,如果您希望对其进行数学运算或作图,则需要将其转换回数字数据类型