create dynamically named objects in a for loop in r and assign dynamic values

You can use mget and stack

# creates a list of all objects with names starting with "Y" followed by 4 digits
l <- mget(x = ls(pattern = "^Y\\d{4}$"))

Now use stack to create a dataframe from the names of that list and the columns names of the dataframes that the list contains

out <- stack(sapply(l, names))

Result

out 
#  values   ind
#1   VAR1 Y2015
#2   VAR2 Y2015
#3   VAR1 Y2016
#4   VAR2 Y2016
#5   VAR1 Y2017
#6   VAR3 Y2017
#7   VAR4 Y2017

If you wish to remove the “Y” and make the ind to numeric, try

out$ind <- as.numeric(sub("Y", "", out$ind))

Change column names

names(out) <- c("file", "year")
out
#   file year
#1 VAR1 2015
#2 VAR2 2015
#3 VAR1 2016
#4 VAR2 2016
#5 VAR1 2017
#6 VAR3 2017
#7 VAR4 2017

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top