Seydou GORO
Seydou GORO

Reputation: 1285

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:

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.

Upvotes: 1

Views: 35

Answers (3)

PaulS
PaulS

Reputation: 25323

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

Upvotes: 1

Tony
Tony

Reputation: 66

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

Upvotes: 1

Andre Wildberg
Andre Wildberg

Reputation: 19088

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

Upvotes: 2

Related Questions