1

I'm very new to R so may still be thinking in spreadsheets. I'd like to loop a list of names from a vector (list) through a function (effect) and append text to the front and end of the name a bit of text ("data$" and ".time0" or ".time1") so it references a specific vector of a dataframe I already have loaded (i.e., data$variable.time0 and data$variable.time1).

Paste just gives me a character named "data$variable.time0" or "data$variable.time1", rather than referencing the vector of the dataframe I want it to. Can I convert this to a reference somehow?

for (i in list){
  function(i)
}

effect <- function(i){
    time0 <- paste("data$",i,".time0", sep = ""))
    time1 <- paste("data$",i,".time1", sep = "")) 

#code continues but not relevant here

}
pomodoro
  • 297
  • 3
  • 12
  • try this `paste("data$",print(i),".time0", sep = ""))` – patL May 03 '18 at 07:39
  • This seems relevant here: [Dynamically select data frame columns using $ and a vector of column names](https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-vector-of-column-names) – Henrik May 03 '18 at 07:44
  • Quick tip: `list()` is a base function of R, try to avoid naming your objects the same as base functions. – LAP May 03 '18 at 07:56

1 Answers1

2

You can use eval(parse(text = "...")) to evaluate characters.

Try

time0 <- eval(parse(text = paste("data$",i,".time0", sep = ""))))

within your loop.

LAP
  • 6,605
  • 2
  • 15
  • 28