Home > Software design >  Put each element of a vector as a column in each dataframe contained in a list
Put each element of a vector as a column in each dataframe contained in a list

Time:03-22

I have a list with dataframes that have the same number of columns and different number of rows. Like this example:

dfs_list <-  list(data.frame(var1 = seq(1:10), var2 = LETTERS[1:10]), 
                  data.frame(var1 = seq(1:20), var3 = LETTERS[1:20]),
                  data.frame(var1 = seq(1:15), var2 = LETTERS[1:15]))

To each of the data frames I need to add a column at the beginning according to a vector that I have with the cities

city <- c("city1", "city2", "city3")

Always the number of dataframes in dfs_list matches the number of elements of the vector city

I made this solution with a for loop

for (i in seq_along(city)) {
  dfs_list[[i]] <- mutate(dfs_list[[i]], city = city[i], .before = 1)
}

I would like to know if there is another solution without the need to use the for loop, since I am finding it a bit slow when I generalize it for a large group of cities.

CodePudding user response:

We may use Map with cbind in base R

dfs_list <- Map(cbind, city = city, dfs_list)

-output

dfs_list
$city1
    city var1 var2
1  city1    1    A
2  city1    2    B
3  city1    3    C
4  city1    4    D
5  city1    5    E
6  city1    6    F
7  city1    7    G
8  city1    8    H
9  city1    9    I
10 city1   10    J

$city2
    city var1 var3
1  city2    1    A
2  city2    2    B
3  city2    3    C
4  city2    4    D
5  city2    5    E
6  city2    6    F
7  city2    7    G
8  city2    8    H
9  city2    9    I
10 city2   10    J
11 city2   11    K
12 city2   12    L
13 city2   13    M
14 city2   14    N
15 city2   15    O
16 city2   16    P
17 city2   17    Q
18 city2   18    R
19 city2   19    S
20 city2   20    T

$city3
    city var1 var2
1  city3    1    A
2  city3    2    B
3  city3    3    C
4  city3    4    D
5  city3    5    E
6  city3    6    F
7  city3    7    G
8  city3    8    H
9  city3    9    I
10 city3   10    J
11 city3   11    K
12 city3   12    L
13 city3   13    M
14 city3   14    N
15 city3   15    O

Or in tidyverse, this can be done with map2 (or if it is a named list, then imap)

library(purrr)
library(dplyr)
map2(dfs_list, city, ~ .x %>% 
      mutate(city = .y, .before = 1))
  •  Tags:  
  • r
  • Related