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. Not very efficient (loop inside loop ... etc), but I think 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)
}
}
Because the string search function used internally is grep
, you can search for names in a non-exact way. It is possible to improve, of course, to leave case-insensitive, ignore accents etc.
The result is a data.frame with a column indicating the number of the element within the list, another indicating the column of the data.frame and a third indicating the line, such as the following:
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