From 31811bec30da7235d466d27be4eedd905d288ad0 Mon Sep 17 00:00:00 2001 From: Marcel Costa Date: Sat, 12 Feb 2022 12:05:04 +0100 Subject: [PATCH] =?UTF-8?q?A=C3=B1adida=20funci=C3=B3n=20perc.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- R/perc.R | 7 +++++++ man/perc.Rd | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 R/perc.R create mode 100644 man/perc.Rd diff --git a/R/perc.R b/R/perc.R new file mode 100644 index 0000000..b7ea5f7 --- /dev/null +++ b/R/perc.R @@ -0,0 +1,7 @@ +perc<-function(x, per100=T){ + if (per100==T){ + return(x*100/sum(x, na.rm = T)) + }else{ + return(x/sum(x, na.rm = T)) + } +} \ No newline at end of file diff --git a/man/perc.Rd b/man/perc.Rd new file mode 100644 index 0000000..38419fe --- /dev/null +++ b/man/perc.Rd @@ -0,0 +1,25 @@ +\name{perc} +\alias{perc} +\title{perc} +\usage{ +perc(x, per100=T) +} +\arguments{ + \item{x}{A numeric vector or an R object but not a factor coercible to numeric by as.double(x).} + \item{perc}{A logical value indicating whether the result must sum 100 (TRUE) or 1 (FALSE).} +} +\description{ +This function the percentages of a numeric vector. +} +\examples{ +v<-c(2,5,10,3) +perc(v) + +# It can be used with dplyr tables +library(tidyverse) +df<-data.frame("X"=c("A","A","B","B"), "Y"=v) +df \%>\% group_by(X) \%>\% summarise(Y=perc(Y)) + +# Or it can be under 1 +df \%>\% group_by(X) \%>\% summarise(Y=perc(Y, per100=F)) +}