Home > Software design >  How to add the same column to each dataframe of my list followin a pattern
How to add the same column to each dataframe of my list followin a pattern

Time:12-10

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:

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.

CodePudding user response:

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

CodePudding user response:

The function you are looking for is lapply. You pass it your list and a function, and it applies your function on each element of the list.

If your list is called l:

l <- lapply(seq_along(l), function(id){
  df <- l[[id]]
  df$Center = id
  return(df)
})

CodePudding user response:

Another solution, based on purrr::imap:

library(tidyverse) 

mylist <- 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)
  )
)

imap(mylist, ~ bind_cols(.x, Center = str_c("Center ",.y)))

#> [[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
  • Related