I made a small change in your data to increase the number of cases:
df1 <- data.frame(nome = c("José da Silva", "Maria da Silva"),
idade = c(45, 54))
df2 <- data.frame(nome_completo = c("Mauro Pereira", "João Paulo", "João Pedro"),
idade = c(30, 12, 1))
df3 <- data.frame(renda = c(1, 2, 3),
idade = c(3, 2, 9),
nome_do_cabra = c("Antônio Augusto", "João Marcos", "João Ivo"))
lista <- list()
lista[[1]] <- df1
lista[[2]] <- df2
lista[[3]] <- df3
See if this function solves your problem. It is not very efficient (loop inside loop... etc), but I believe it does work.
procura_nome <- function(x, pattern){
list_result <- list()
element_list_i = 1
for(j in 1:length(x)){
for(k in 1:ncol(x[[j]])){
linhas_result <- grep(x = x[[j]][,k], pattern = pattern)
if(length(linhas_result) > 0){
list_result[[element_list_i]] <- cbind(j, k, linhas_result)
element_list_i = element_list_i + 1
}
}
}
if(length(list_result) >0 ){
matrix_result <- purrr::reduce(list_result, rbind)
df_result <- as.data.frame(matrix_result)
names(df_result) <- c("numero_lista", "numero_coluna", "numero_linha")
return(df_result)
}else{
return(NULL)
}
}
Since the string search function used internally is the grep
, you can search for names in a way not exact. It is possible to improve, of course, to make case-insensitive, ignore accents etc.
The result is a data.frame with a column indicating the element number within the list, another indicating the data.frame column, and a third indicating the row, such as the next one:
procura_nome(lista, "João")
### numero_lista numero_coluna numero_linha
### 1 2 1 2
### 2 2 1 3
### 3 3 3 2
### 4 3 3 3
This answer is good, but in my case I have a list with 250 elements, I needed something that would return me only the position where the expression is.
– Jessica Voigt