Guest User

Untitled

a guest
Dec 11th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. df$eval<- apply(df[,cods], 1, function(r) any(r == 89))
  2.  
  3. set.seed(2018)
  4. df <- data.frame(x1=sample(85:95, 10),
  5. x2=sample(88:90, 10, replace = TRUE),
  6. x3=sample(85:95, 10),
  7. x4=sample(85:95, 10),
  8. x5=sample(85:95, 10)
  9. )
  10.  
  11. df$eval <- apply(df, MARGIN=1, FUN=function(x) {sum(x[which(x==89)+1], na.rm = TRUE)})
  12. df
  13.  
  14. x1 x2 x3 x4 x5 eval
  15. 1 88 89 87 86 94 87
  16. 2 89 89 90 93 92 179
  17. 3 85 90 86 85 90 0
  18. 4 86 90 85 88 89 0
  19. 5 95 90 94 92 95 0
  20. 6 92 89 88 89 85 173
  21. 7 91 88 93 94 91 0
  22. 8 93 89 91 90 93 91
  23. 9 87 90 89 95 88 95
  24. 10 90 90 92 91 86 0
  25.  
  26. sumar_despues_de_x <- function(datos, valor)
  27. {
  28. vec <- matrix(ncol = ncol(datos), nrow = nrow(datos)) #Predefino la matriz
  29. for (i in 2:ncol(df))
  30. {
  31. vec[,i] <- ifelse(datos[,i-1]==valor, datos[,i], NA) #Retengo sólo los valores posteriores a 89
  32. }
  33. rowSums(vec, na.rm = TRUE) #Saco un vector con las sumas de filas de la matriz filtrada
  34. }
  35.  
  36. df$eval <- sumar_despues_de_x (df, 89)
  37.  
  38. set.seed(2018)
  39. df <- data.frame(x1=sample(89:91, 10, replace = TRUE), #Aumento la probabilidad de 89
  40. x2=sample(85:95, 10),
  41. x3=sample(89:91, 10, replace = TRUE),
  42. x4=sample(90:100, 10))
  43.  
  44. library(tidyverse)
  45. library(data.table) #para transpose()
  46. df %>%
  47. data.table::transpose() %>% #pq `purrr` tiene una función con el mismo nombre.
  48. gather() %>%
  49. group_by(key) %>%
  50. mutate(filtrado = ifelse(lag(value)==89, value, NA)) %>%
  51. summarise(suma_filtrada = sum(filtrado, na.rm = T)) %>%
  52. mutate(key = str_remove(key, "V")) %>%
  53. arrange(as.numeric(key)) %>%
  54. select(-key) %>%
  55. bind_cols(df, .)
  56.  
  57. x1 x2 x3 x4 suma_filtrada
  58. 1 90 89 89 91 180
  59. 2 90 91 90 98 0
  60. 3 89 93 89 90 183
  61. 4 89 90 89 93 183
  62. 5 90 92 91 97 0
  63. 6 89 88 90 94 88
  64. 7 90 86 89 99 99
  65. 8 89 87 91 95 87
  66. 9 91 94 90 100 0
  67. 10 90 95 89 96 96
Add Comment
Please, Sign In to add comment