For several days i am trying to get the correctly counted output for a combination of nested ifelse and nested loops. I suppose either my nesting is totaly wrong or the way I try to count the output, maybe both.
ifelse.1 = function(input_matrix) {
result = 1
output = 0
sum_output = 0
for(i in 1:dim(input_matrix)[1]){
for(j in 1:dim(word_list_matrix-one)[1]){
for(k in 1:dim(word_list_matrix_two)[1]){
ifelse(str_detect(input_matrix[i], ("word")) == TRUE
& str_detect(input_matrix[i], word_list_matrix_one[j]) == TRUE
& str_detect(input_matrix[i], word_list_matrix_two[k]) == TRUE,
output[i] <- output[i] + result,
ifelse(
str_detect(input_matrix[i], word_list_matrix_three[j]) == TRUE
& str_detect(input_matrix[i], word_list_matrix_two[k]) == FALSE,
output[i] <- output[i] + result, NA))
sum_output = output[i]
} # k-loop
} # j-loop
} # i-loop
return(sum_output)
}
The code is about detecting certain strings (via the str_detect
function of the package stringr
) in multiple rows of multiple one column matrices.
So in the first row [i]
of input_matrix
the string given from row [j]
in word_list_matrix
should be detected.
Whenever one of the above mentioned ifelse is true, +1 should be added to the output, at the end of all i cycles the sum of the output should be returned.
Problem is I either get NA
as an answer, or (for some variants of this code) I get more output counted than I gave input.
I know that ifelse should be able to compute vectors, which could lead to not needing the loops, but despite I never got that working, the matrices I have to compute are not of the same length.
I hope that I managed to deliver a good, reproducible question with enough detail. Thank you very much for your time.