Home > Net >  How do I loop over a list of strings in R?
How do I loop over a list of strings in R?

Time:11-11

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:

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?

CodePudding user response:

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)
}

CodePudding user response:

You can do this without using the loop and in one line only. See;

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

lapply(List, FUN = function(x) as.numeric(grepl(x, col1)))
  • Related