Vitomir
Vitomir

Reputation: 295

Apply a function dynamically to n different objects

I am working in R.

I have n different objects all with the same name structure paste0("df",j) for j = 1,...,n (i.e. df1, df2, df3, ...).

To each one of them, I want to apply a user-defined function (let's assume its only argument is the object itself).

Usually, I use this:

for (i in (1:n)){
 assign(paste0("u", 1), function(eval(parse(text = paste0("df",i)))))
}

Nevertheless, I get the following error:

Error in parse(text = paste0("df", j)) : 
  unused argument (text = paste0("df", j))

Does anyone have a solution for this? I would appreciate if the solution would not involve the eval(parse(text = paste0("something")))) trick which I personally find not that practical.

Upvotes: 1

Views: 52

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76673

Something like this?

  1. Get the objects names with that name structure into a character vector;
  2. mget the data sets;
  3. lapply the function to each data set.

The code would be:

df_names <- ls(pattern = "^df\\d+$")
u_list <- lapply(mget(df_names), function(DF){
  # do this and that
  DF[["x"]] <- DF[["x"]] + 100
  DF
})
u_list
#$df1
#    x
#1 101
#2 102
#3 103
#4 104
#5 105
#
#$df2
#    x
#1 111
#2 112
#3 113
#4 114
#5 115

If the names of the result dataframes need to be "u" followed by a number,

names(u_list) <- paste0("u", seq_along(u_list))

Data

df1 <- data.frame(x = 1:5)
df2 <- data.frame(x = 11:15)

Upvotes: 1

Related Questions