How to catch and name Tibbles using a for-loop from a larger data frame.

I'm subsetting a data-frame by rows using a for-loop.

The example input data is "Bom_test.csv" and can be accessed using a dropbox link (see below). The desired output is four Tibbles.

In the example, the first output Tibble consists of rows 1 to five. The starting row for making the remaining three Tibbles is described in the vector.

I'm using the 'Search' to capture the variable name from column A for each subsetted table.

The code pasted below gives no error messages, however only the last tibble is saved.

I have two questions
a) How do I 'catch' (ie. save) all four tibbles from the loop? and
b) How can I name tibbles using the term "Searchi"? In this example, Searchi is "Item1", "Component1", "Component9" and "Component14".

Many thanks for your help.



# Input data can be found at

#Read in data
x <- read_csv("Bom_test.csv")

# A loop to make output tibbles.
loop_values <- c(1, 6, 11, 16)                                # This is the vector of values to loop through.
  for ( i in loop_values){
    Searchi <- x %>%                              
      slice(i) %>% select(1)                                        # Finds first observation in column 1 ie. "item 1"
    Searchi = as.character(Searchi)                      # Changes "item 1" into a string that can be searched for.
    Tibble <- x %>%                                                    # Searches for 'item 1" and makes tibble of 'item 1"
      filter(str_detect(Assembled_Product_Code, Searchi))

A loop is not the best way to accomplish this task, take a look at this alternative method


x <- read.csv("BOM_test.csv")

x %>% 
    nest_by(Assembled_Product_Code) %>% 
    mutate(data = set_names(list(data), Assembled_Product_Code)) %>%
    list2env(x = .$data, envir = globalenv())

Note: Next time please provide a proper REPRoducible EXample (reprex) illustrating your issue.

Thanks very much, Andrés. Best, Jenny

And yes, I my next help request will include a reprex.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.