How to use dplyr for programming

I like dplyr for data manipulation, but I don't understand how to use it for programming. For example, to rescale some variables, we could do:

mutate(cars, speed.scaled = scale(speed), dist.scaled = scale(dist))

Very cool. But now suppose I want to write a function that uses mutate to scale all variables in a data frame. How do I create the ... argument? The best thing I can come up with is something like:

fnargs <- lapply(names(cars), function(x){call("scale", as.name(x))})
names(fnargs) <- paste0(names(cars), ".scaled")
do.call(mutate, c(.data=as.name("cars"), fnargs))

Or is there an alternative interface that is more programming friendly?

Answers


Easy peasy: use mutate_each(cars, funs(scale)) or apply(cars, 2, scale).


This can be done in base R like this:

cars.scaled <- as.data.frame(scale(cars))

or

cars.scaled <- replace(cars, TRUE, lapply(cars, scale))

or

cars.scaled <- cars
cars.scaled[] <- lapply(cars, scale)

The first one above can be translated to work with %>% like this:

cars.scaled <- cars %>% scale %>% as.data.frame

Need Your Help

TextSecure Server,Signal Android App and Push Server Configuration

java android push-notification google-cloud-messaging

i want to build my own secure messagging service (TextSecure Server+PushServer+Android App+another necessary project)