'How to loop through a list of values and add it in the designated areas of the code?

I have a list of string values

c("String1","String2","String3")

How do I create a loop or using lapply that would add the list values into areas of the code I want them to be added to?

DataFrame_String1<- DataFrame %>%
    filter(.,ID=="String1")

DataFrame_String2<- DataFrame %>%
    filter(.,ID=="String2")

DataFrame_String3<- DataFrame %>%
    filter(.,ID=="String3")

Note that the values in the list are added in the title of the dataframe and in the ID section.



Solution 1:[1]

If we need a loop, then loop over the vector with lapply or purrr::map

library(purrr)
library(dplyr)
library(stringr)
lst1 <- map(c("String1", "String2", "String3"), ~ DataFrame %>%
           filter(ID == .x))
names(lst1) <- str_c("DataFrame_", c("String1", "String2", "String3"))

It may be better to keep it in a list. But, we can create objects with list2env from a named list

list2env(lst1, .GlobalEnv)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akrun