How to test multiple data.frames and establish a maximum score of the tests for a certain position? #R

2

Given the following data.frames:

 library(zoo)
 A<-data.frame(x1=(0:9),x2=rep(0:1,5),x3=rep(0:4,2))
 B<-apply(A, 2, function(x) rollapply(x, width = 2, FUN = sum, fill = NA, align = 'r', na.rm=TRUE))
 C<-apply(A, 2, function(x) rollapply(x, width = 3, FUN = sum, fill = NA, align = 'r', na.rm=TRUE))
 D<-apply(A, 2, function(x) rollapply(x, width = 4, FUN = sum, fill = NA, align = 'r', na.rm=TRUE))

Since B, C and D are the result of the accumulation of values of A, performed with the use of the window function rollapply , varying from one to one of 2 to 4.

I want to test when A, B, C, and D are the same, that is, A == B, A == B == C and A == B == C == D. After this, the test results should be converted into notes, for example:

 Teste       | Nota
 "A==B"      |  1 
 "A==B==C"   |  20
 "A==B==C==D"|  300

By storing each note in a data.frame in its respective position, as for "A == B":

      x1 x2 x3
 [1,] NA NA NA
 [2,]  1  1  1
 [3,]  0  0  0
 [4,]  0  1  0
 [5,]  0  0  0
 [6,]  0  1  0
 [7,]  0  0  1
 [8,]  0  1  0
 [9,]  0  0  0
[10,]  0  1  0

After the generation of each note (data.frame), I need to know the maximum grade for each cell. How do I do this?

    
asked by anonymous 01.02.2016 / 08:30

1 answer

1

If I understand correctly, the code below does what you want. But the data seems not to be ideal, because there is no case of A==B==C much less A==B==C==D . If you have more appropriate real data you can see if it worked at all.

I thought it best to explain line by line rather than all at once.

library(zoo)

A <- data.frame(x1 = (0:9), x2 = rep(0:1, 5), x3 = rep(0:4, 2))

# Colocando todas matrizes acumuladas em uma lista única
BCD <- lapply(setNames(2:4, c("B", "C", "D")), function(i) {
  apply(A, 2, function(x) rollapply(x, width = i, FUN = sum, fill = NA, align = 'r', na.rm=TRUE))
})

# Definindo as notas para cada nível de comparação
notas <- c(1, 20, 300)

# Realizando a comparação de forma recursiva
comps <- lapply(1:3, function(j) {
  # Compara A com todas os elementos de BCD e 1 até j (1:1, 1:2, 1:3)
  equals <- Reduce("==", append(list(A), BCD[1:j]))
  # Coloca a nota em função da comparação
  comp <- ifelse(equals, notas[j], 0)
  # Transforma os NA em 0, depende do que você deseja.
  comp[is.na(comp)] <- 0
  # Retorna comp
  comp
})

# Roda nas matrizes de comps mantendo o máximo de cada posição
all.max <- do.call(pmax, comps)
all.max

#       x1 x2 x3
#  [1,]  0  0  0
#  [2,]  1  1  1
#  [3,]  0  0  0
#  [4,]  0  1  0
#  [5,]  0  0  0
#  [6,]  0  1  0
#  [7,]  0  0  1
#  [8,]  0  1  0
#  [9,]  0  0  0
# [10,]  0  1  0

As I said, the result only has 1 notes because there is only A==B .

    
01.02.2016 / 20:56