Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading