[R] Iteration over variables

G.Maubach at weinwolf.de G.Maubach at weinwolf.de
Tue Sep 6 11:54:18 CEST 2016


Hi All,

I would like to write a program that iterates over a set of dynamically 
generated variables and produces some stats or prints parts of the data.

# --- data
v_turnover_2011 <- c(10, 20, 30, 40 , 50)
v_customer_2011 <- c(0, 1, NA, 0, 1)
v_turnover_2012 <- c(10, 20, 30, 40 , 50)
v_customer_2012 <- c(0, 1, NA, 0, 1)
d_dataset <- data.frame(v_turnover_2011, v_turnover_2012,
                        v_customer_2011, v_customer_2012)

# -- Aim is to iterate over dynamically generated variables and compute
# -- statistics or print parts of the data

# -- Does not produce any output
for (year in 2011:2012) {
  head(d_dataset[, c(paste0("v_turnover_", year),
                     paste0("v_customer_", year))])
}

# -- Does not produce any output
aux_func <- function(year) {
  head(d_dataset[, c(paste0("v_turnover_", year),
                     paste0("v_customer_", year))])
}

for (year in 2011:2012) {
  aux_func(year = year)
}


d_results <- data.frame()
for (year in 2011:2012) {
  d_results <- rbind(d_results,
                     paste0("mean", year) = mean(d_dataset[, 
c(paste0("v_turnover_", year))]))
}

Is there a way to iterate over variables and compute statistics and print 
parts of the dataset?

Kind regards

Georg



More information about the R-help mailing list