user35131
user35131

Reputation: 1134

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.

Upvotes: 1

Views: 27

Answers (1)

akrun
akrun

Reputation: 887148

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)

Upvotes: 1

Related Questions