[R] Applying function to only numeric variable (plyr package?)

Jan van der Laan rhelp at eoos.dds.nl
Wed Oct 12 15:50:59 CEST 2011


plyr isn't necessary in this case. You can use the following:

cols <- sapply(df, is.numeric)
df[, cols] <- pct(df[,cols])


round (and therefore pct) accepts a data.frame and returns a  
data.frame with the same dimensions. If that hadn't been the case  
colwise might have been of help:

library(plyr)
pct.colwise <- colwise(pct)
df[, cols] <- pct.colwise(df[,colwise])

HTH,

Jan



Quoting Michael.Laviolette at dhhs.state.nh.us:

>
> My data frame consists of character variables, factors, and proportions,
> something like
>
> c1 <- c("A", "B", "C", "C")
> c2 <- factor(c(1, 1, 2, 2), labels = c("Y","N"))
> x <- c(0.5234, 0.6919, 0.2307, 0.1160)
> y <- c(0.9251, 0.7616, 0.3624, 0.4462)
> df <- data.frame(c1, c2, x, y)
> pct <- function(x) round(100*x, 1)
>
> I want to apply the pct function to only the numeric variables so that the
> proportions are computed to percentages, and retain all the columns:
>
>   c1 c2   x1   x2
> 1  A  Y 52.3 92.5
> 2  B  Y 69.2 76.2
> 3  C  N 23.1 36.2
> 4  C  N 11.6 44.6
>
> I've been approaching it with the ddply and colwise functions from the plyr
> package, but in that case each I need each row to be its own group and
> retain all columns. Am I on the right track? If not, what's the best way to
> do this?
>
> Thanks in advance,
> M. L.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list