How to test multiple data.frames and set a maximum test score for a certain position? #R

Asked

Viewed 78 times

2

Considering the following date.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))

Where B, C and D are the result of the accumulation of A values, carried out using the mobile window function rollapply, ranging from one in one of 2 to 4.

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

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

Storing each note in a date.frame at 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 to perform this procedure?

1 answer

1


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

I thought it better to explain line by line 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 has only grades 1 because it only exists A==B.

  • @ It worked! I’m trying to generalize to cases with more matrices. As soon as I can I’ll upload the true data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.