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

How to add the same column to each dataframe of my list followin a pattern

Here is a representation of my list of dataset.
Each dataset has two columns: Year and Age

list(
  
  data.frame(
    year=c(2010,2010,2011),
    Age=c(23,24,25)
  ),
  data.frame(
    year=c(2010,2010,2011),
    Age=c(23,24,25)
  ),
  data.frame(
    year=c(2010,2010,2011),
    Age=c(23,24,25)
  )
)

I want to add to each dataset a column= Center

The center number must be the index of the dataset in the list:

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

Here is below the expected list

[[1]]
  year Age   Center
1 2010  23 Center 1
2 2010  24 Center 1
3 2011  25 Center 1

[[2]]
  year Age   Center
1 2010  23 Center 2
2 2010  24 Center 2
3 2011  25 Center 2

[[3]]
  year Age   Center
1 2010  23 Center 3
2 2010  24 Center 3
3 2011  25 Center 3

I have no idea how to do this automatically through the list.

>Solution :

You can try lapply to cycle through the list

lapply( seq_along(lis), function(x) cbind( lis[[x]], Center=paste("Center",x)) )
[[1]]
  year Age   Center
1 2010  23 Center 1
2 2010  24 Center 1
3 2011  25 Center 1

[[2]]
  year Age   Center
1 2010  23 Center 2
2 2010  24 Center 2
3 2011  25 Center 2

[[3]]
  year Age   Center
1 2010  23 Center 3
2 2010  24 Center 3
3 2011  25 Center 3
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