myth007
myth007

Reputation: 23

Looping through data frames and add new columns with values based on part of data frame name in R

I have a several data frames named as such: gkz.01.1999, gkz.01.2000..., gkz.02.1999, gkz.02.2000... The data looks like this:

         col1  col2  col3  col4
1 under 1 year 14091 13394 27485
2       1 year 14476 13802 28278
3      2 years 15420 14336 29756
4      3 years 15285 14437 29722
5      4 years 14704 13901 28605
6      5 years 14966 14016 28982

How I can loop through all data frames (or use apply) and add two new columns to each data frame, where the values of the first new column (gkz) are equal to the first two digits of the data frame name and the values in the second new column (year) are equal to the last 4 digits of the data frame name? For example, for data frame gkz.01.1999:

         col1  col2  col3  col4   gkz     year
1 under 1 year 14091 13394 27485  01      1999
2       1 year 14476 13802 28278  01      1999
3      2 years 15420 14336 29756  01      1999
4      3 years 15285 14437 29722  01      1999
5      4 years 14704 13901 28605  01      1999
6      5 years 14966 14016 28982  01      1999

Thanks in advance.

Upvotes: 1

Views: 96

Answers (1)

akrun
akrun

Reputation: 887891

We get the data.frames into a list.

#get the objects that start with 'gkz' as strings
nm1 <- ls(pattern = "gkz\\.\\d+")
#use mget to get the values of the objects in a list
lst <- mget(nm1)
#extract the numbers that follow the gkz using sub
nm2 <- sub("^[^.]+\\.([^.]+).*", "\\1", nm1)
#extract the last 4 numbers with sub
nm3 <- sub(".*\\.(\\d+)$", "\\1", nm1)

#create new columns in the list of data.frame with Map
lst1 <- Map(cbind, lst, gkz = nm2, year = as.integer(nm3))

Upvotes: 1

Related Questions