Heisenberg Heisenberg - 5 months ago 31
R Question

Why do I have to use assign() instead of eval(parse(text=())) in R

The problem arises when I want to use a loop to assign new values to several data frames.

I know the correct way is

for (df.name in c('df1', 'df2', 'df3')) {
assign(df, new.value)

My question is, why can't I do this

for (df.name in c('df1', 'df2', 'df3')) {
eval(parse(text=df.name)) <- new.value



You can use eval/parse:

eval(parse(text= paste(df.name, "<- new.value")))

The error that you were getting,

target of assignment expands to non-language object

is because eval(parse(text=df.name)) returns the variable df1, which isn't an R expression to be evaluated.

Please remember that eval/parse is dark, dangerous, magic that leads to unmaintainable zombie code. If you can find a different way to write your code, choose that instead.

As mentioned in the comments, if you have several data frames with similar properties, it is often easier to work with them as a list.

df_list <- list(df1 = df1, df2 = df2, df3 = df3)

Then you can use lapply to manipulate each data frame in a loop, or combine them into a single data frame using rbind or dplyr::bind_rows.