R 将列i到j转换为百分比

R 将列i到j转换为百分比,r,dplyr,R,Dplyr,假设我有以下数据: 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)) 但是我希望有更好的方法,特别是对于我有很多列而不是只有两列的情况 我试着对每一个进行变异,但我做错了 df1 %>% mutate_

假设我有以下数据:

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))
但是我希望有更好的方法,特别是对于我有很多列而不是只有两列的情况

我试着对每一个进行变异,但我做错了

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%
如果需要从获取百分比中筛选出NAs

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%
df1%>%
每个(funs)(try)(如果其他(!is.na(.),百分比(.),na),
silent=TRUE)),-name)
#将某个变量命名为othervariable
#1 A1 13.4%53.4%
#2 A1 54.8%
#3 B1 36.9%36.9%
#4 B1 33.3%

这里有一种使用自定义函数的替代方法。此函数只修改数值向量,因此无需担心
try
或删除非数值列。它还将通过defult处理
NA
s

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%
myfun%每个变异(funs(myfun))
#将某个变量命名为othervariable
#1 A1 13.4%53.4%
#2 A1 54.8%
#3 B1 36.9%36.9%
#4 B1 33.3%

我想知道在哪种情况下,
df1%>%变异(funs(百分比),-name)
不会do@DavidArenburg可能带有
因子
。例如,
df1%>%mutate(val=percent(factor(somevariable))
噢,对了,它似乎返回并出错了。但是我的函数不起作用。不知道发生了什么better@DavidArenburg使用您的函数,返回带有警告的输出,但使用NAs时,由于我知道的Factory存在问题,尽管在因子上使用替代方法没有更好的效果
df1%>%mutate_each(funs(try(percent(.),silent=TRUE))
我认为如果提前返回,函数会稍微干净一些,例如,
if(!is.numeric(x))返回(x)
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%