Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subsequent ID in list of dfs

I have a list of dfs like:

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)

df1 <- data.frame(Name, Age)

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)
df2 <- data.frame(Name, Age)

list <- list(df1, df2)

I want to create a subsequent ID through all DFs. My desired Output should look like:

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)
ID <- c(1:5)

df1 <- data.frame(Name, Age, ID)

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)
ID <- c(5:9)
df2 <- data.frame(Name, Age, ID)
list <- list(df1, df2)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

(I named it list1 instead of list, not wanting to confuse variables/functions 🙂

I’m assuming df2 should start at nrow(df1) + 1, not at nrow(df1).

lens <- sapply(list1, nrow)
list1 <- Map(function(X, fm, len) transform(X, ID = fm + seq_len(len)),
             list1, c(0, lens[-length(lens)]), lens)
list1
# [[1]]
#    Name Age ID
# 1   Jon  23  1
# 2  Bill  41  2
# 3 Maria  32  3
# 4   Ben  58  4
# 5  Tina  26  5
# [[2]]
#    Name Age ID
# 1   Jon  23  6
# 2  Bill  41  7
# 3 Maria  32  8
# 4   Ben  58  9
# 5  Tina  26 10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading