0
votes

I'm trying to loop through several data frames that all have a standard name other than the last character which is an integer. I am trying to loop through the data frames and perform a task on each but I don't know how to reference each data frame by name.

for(i in 1:length(xyz)){
    approx(df & i & $X, df & i & $Y, xout=aim)
}

that is essentially the format I want where each iteration will increase the number i and therefore the name of the data frame eg. df1$X, df2$X, df3$X, df4$X...

I know this code won't work but I don't know what will

1
put them in a list and apply (lst1 <- mget(ls(pattern = 'df[0-9]+')); lapply(lst1, function(i) approx(i$X, ...))) - Sotos
A rather hacky version to get your own loop to work would be approx(eval(parse(text = paste0("df", i, "$X"))), eval(parse(text = paste0("df", i, "$Y"))), xout = aim). But listen to @Sotos and use a list. - LAP
I don't entirely understand the method being used here by @Sotos how is the function being applied here? - tombat7112
I understand the method using by @Leo using functions to concatenate the variable names but I don't understand how that list method would contain the information and how the approximation function would be applied - tombat7112
@tombat7112: The mget(ls(...)) will put all your data.frames in a list called lst1. Afterwards you apply the function function(i) approx(i$X, i$Y, xout = aim) over the list of your data.frames with the lapply() call and either print the output, or save it to another list by assigning output <- lapply(...). - LAP

1 Answers

0
votes

The way I 'd do it, is to put them in a list and iterate. Using mget we fetch the objects of interest by specifying a pattern in ls() which in your case would be df[0-9]+. Finally use lapply to iterate.

lst1 <- mget(ls(pattern = 'df[0-9]+'))
lapply(lst1, function(i) approx(i$X, i$Y, xout = aim))