1

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.

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

5 Comments

Where is a good resource to described how to interpret/use all those chicken scratches? :)
@akaDrHouse Thanks, I forgot about it. Now, updated
Thanks @akrun. That is very helpful. I was actually really interested in an online manual that you could recommend. I see these used all the time in answers, but for the most part, they are still Greek to me.
@akaDrHouse If you are looking for regex, then regular-expressions.info/tutorial.html is one option
This worked great. I had tried creating a list and then using sub, but could not get it to work. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.