Use values from a dataframe in ifelse

1

I have the following scenario:

Data frame - Resources:

recursos <- as.data.frame(c("server01","server02","server03"));  
colnames(recursos) <- "Server"

Data frame - Events:

eventos <- as.data.frame(c("falha no server01","erro no server01","falha no server02","erro no server03"));  
colnames(eventos) <- "Eventos";  
eventos <- dplyr::mutate(eventos, Server = "")

My object is popular in the Server column in the data frame events, based on the mapped servers in the data frame resource. In the solution below, I can fill in using a unique value. But it's not what I need yet.

eventos$Server <- ifelse(grepl("server01", eventos$Eventos), "server01", "")

I thought of running a for (server in $ Server resources) by changing in grep, by a variable. But I could not do it this way. Could someone help me?

Thank you in advance.

    
asked by anonymous 04.05.2017 / 19:23

2 answers

0

Updating the solution:

procura <- as.data.frame(sapply(as.character(recursos$Server), function(x) grepl(x, eventos$Eventos)), stringsAsFactors = F)

# Adiciona uma coluna "Missing" para os casos que não tem nenhum 'recurso'
procura$Missing <- F
procura$Missing[rowSums(procura)==0] <- T

for(i in 1:nrow(eventos)) {
  eventos$Server[i] <- colnames(procura)[which(procura[i,]==T)]
}

This will work regardless of the number of servers in the database recursos$Server

    
04.05.2017 / 19:53
1

If events contain the correct information about the servers, as in the example provided, just use the regmatches function together with the relevant regular expression to extract the substrings of interest.

eventos <- dplyr::mutate(eventos, Server = regmatches(Eventos, regexpr('server[0-9]+', Eventos)))

Although computationally costly, you can compare the words in each message of the variable Eventos with the list in Server

In a row:

eventos <- dplyr::mutate(eventos,
                         Server = unlist(lapply(
                         strsplit(as.character(eventos$Eventos), '\s'),
                         function(x) x[which(x %in% recursos$Server)])))

Assuming, of course, that server names in Eventos are always equal and unique to each entry.

    
04.05.2017 / 20:26