[R] Creating variables on the fly

G.Maubach at gmx.de G.Maubach at gmx.de
Fri Apr 22 17:52:01 CEST 2016


Hi all,

I would like to use a loop for tasks that occurs repeatedly:

# Groups 
# Umsatz <= 0: 1 (NICHT kaufend) 
# Umsatz > 0: 2  (kaufend) 
for (year in c("2011", "2012", "2013", "2014", "2015")) { 
  paste0("Kunden$Kunde_real_", year) <- (paste0("Kunden$Umsatz_", year) <= 0) * 1 + 
                                        (paste0("Kunden$Umsatz_", year) >  0) * 2 
  paste0("Kunden$Kunde_real_", year) <- factor(paste0("Kunden$Umsatz_", year), 
                                               levels = c(1, 2), 
                                               labels = c("NICHT kaufend", "kaufend")) 
  } 

This actually does not work due to the fact that the expression "paste0("Kunden$Kunde_real_", year)" ist not interpreted as a variable name by the R script language interpreter.

Is there a way to assembly variable names on the fly in R?

Regards

Georg



More information about the R-help mailing list