user1886721 user1886721 - 3 months ago 21
R Question

Shorthand for multiple assignments in R

I have functions that load datasets that are pretty repetitive for cleaning data.

load_data = function(f){
data = read.csv(f)
data$x = (data$a - data$b)/1000
data$y = (data$c - data$d)/1000
data$z = (data$e - data$f)/1000
data
}


Is there any syntactic sugar in R that can make this process less verbose?

The code works, there is no performance problem, but when you have to do the same operation dozens of times, it is less than optimal to modify.

Answer

A little more readable / less verbose:

load_data <- function(f){
    within(read.csv(f), {
        x <- (a - b) / 1000
        y <- (c - d) / 1000
        z <- (e - f) / 1000
    })
}
Comments