假设我有以下数据:
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)
谢谢!
答案 0 :(得分:6)
这是使用自定义功能的替代方法。此函数仅修改数字向量,因此无需担心try
或删除非数字列。它还将通过defult处理NA
个
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%
答案 1 :(得分:3)
尝试
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%