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 do I loop over a list of strings in R?

I want to create a list that contains vectors that display either a 1 or a 0 depending on whether a certain character is present.
The data has the following form:

list <- list('a', 'b', 'c', 'd', 'e')
col1 <- c('ta', 'ta', 'tb', 'tb', 'tb', 'tc', 'td', 'te')

What I want is a list for all elements of ‘list’ that contains a vector displaying a 1 when the element of list is present in the element of col1 and a 0 when it is not.
For ‘a’ this vector will look like (1,1,0,0,0,0,0,0) for example.

My question is why the following loop does not work:

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

test <- list()  
for (i in list){
  test[[i]] <- ifelse(grepl(list[i], col1), 1, 0)
}

This loop returns a list with only zeroes.

However, when I run part of the loop individually it does give the correct result:

ifelse(grepl(list[1], col1), 1, 0)

This does in fact return the vector I want: (1,1,0,0,0,0,0,0).

How do I loop over a list of strings in R correctly?

>Solution :

List <- list('a', 'b', 'c', 'd', 'e')
col1 <- c('ta', 'ta', 'tb', 'tb', 'tb', 'tc', 'td', 'te')

test <- list()  
for (i in 1:length(List)){
  test[[i]] <- ifelse(grepl(List[i], col1), 1, 0)
}
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