Reputation: 295
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
Reputation: 76673
Something like this?
mget
the data sets;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