将列 i 到 j 转换为百分比

Convert columns i to j to percentage

假设我有以下数据:

df1 <- data.frame(name=c("A1","A1","B1","B1"),
                  somevariable=c(0.134,0.5479,0.369,NA),
                  othervariable=c(0.534, NA, 0.369, 0.3333))

在这个例子中,我想将第 2 列和第 3 列转换为百分比(保留一位小数)。我可以用这段代码来做:

library(scales)
df1 %>%
  mutate(somevariable=try(percent(somevariable),silent = T),
         othervariable=try(percent(othervariable),silent = T))

但我希望有更好的方法,特别是对于我有很多列而不是只有 2 列的情况。

我尝试了 mutate_each 但我做错了......

df1 %>%
  mutate_each(funs = try(percent(),silent = T), -name)

谢谢!

尝试

df1 %>% 
    mutate_each(funs(try(percent(.), silent=TRUE)), -name)
#   name somevariable othervariable
#1   A1        13.4%         53.4%
#2   A1        54.8%           NA%
#3   B1        36.9%         36.9%
#4   B1          NA%         33.3%

如果您需要从获取百分比中过滤掉 NA,

df1 %>% 
    mutate_each(funs(try(ifelse(!is.na(.), percent(.), NA), 
                       silent=TRUE)),-name)
#   name somevariable othervariable
#1   A1        13.4%         53.4%
#2   A1        54.8%          <NA>
#3   B1        36.9%         36.9%
#4   B1         <NA>         33.3%

这是使用自定义函数的替代方法。此函数只会修改数字向量,因此无需担心 try 或删除非数字列。它还将默认处理 NAs

myfun <- function(x) {
  if(is.numeric(x)){ 
    ifelse(is.na(x), x, paste0(round(x*100L, 1), "%")) 
  } else x 
}

df1 %>% mutate_each(funs(myfun))
#   name somevariable othervariable
# 1   A1        13.4%         53.4%
# 2   A1        54.8%          <NA>
# 3   B1        36.9%         36.9%
# 4   B1         <NA>         33.3%