Stack tibbles in a loop

Viewed 38

I have various spss-datasets (survey data) and for each dataset there are a number of waves (one wave for each month):

Let's assume that I have four datasets (1 to 4) and two waves for each (_W1 and _W2):

datasets <- c("dataset1_W1.sav", "dataset1_W2.sav", 
              "dataset2_W1.sav", "dataset2_W2.sav",
              "dataset3_W1.sav", "dataset3_W2.sav",
              "dataset4_W1.sav", "dataset4_W2.sav")

datasets

My goal is to stack all waves of each dataset (dataset1_W1 and dataset1_W2; dataset2_W1 and dataset2_W2; etc.). In order to do so I read the files using haven::read_spss(filename) and then I stack them using dplyr::bind_rows(df1, df2).

Now, I'd like to create a tibble for each dataset:

library(dplyr)
library(haven)

ds1_1 <- haven::read_spss("dataset1_W1.sav")
ds1_2 <- haven::read_spss("dataset1_W2.sav")
dataset1_all <- dplyr::bind_rows(ds1_1, ds1_2) 

ds2_1 <- haven::read_spss("dataset2_W1.sav")
ds2_2 <- haven::read_spss("dataset2_W2.sav")
dataset2_all <- dplyr::bind_rows(ds2_1, ds2_2) 

etc.

But how can I create those tibbles (dataset1_all, data2_all etc.) automatically? I've read that I should avoid dynamic variable names.

1 Answers

This will create a named list of dataframes, where each element is a binded dataset from both waves:

library(tidyverse)
datasets <- c("dataset1_W1.sav", "dataset1_W2.sav", 
              "dataset2_W1.sav", "dataset2_W2.sav",
              "dataset3_W1.sav", "dataset3_W2.sav",
              "dataset4_W1.sav", "dataset4_W2.sav")

dataset_id <- str_extract(datasets, "[^0-9]*[0-9]")

list_of_dfs <- datasets %>% 
  split(dataset_id) %>% 
  map_depth(.depth = 2,. f = haven::read_spss) %>% 
  map(bind_rows)
Related