Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- df$eval<- apply(df[,cods], 1, function(r) any(r == 89))
- set.seed(2018)
- df <- data.frame(x1=sample(85:95, 10),
- x2=sample(88:90, 10, replace = TRUE),
- x3=sample(85:95, 10),
- x4=sample(85:95, 10),
- x5=sample(85:95, 10)
- )
- df$eval <- apply(df, MARGIN=1, FUN=function(x) {sum(x[which(x==89)+1], na.rm = TRUE)})
- df
- x1 x2 x3 x4 x5 eval
- 1 88 89 87 86 94 87
- 2 89 89 90 93 92 179
- 3 85 90 86 85 90 0
- 4 86 90 85 88 89 0
- 5 95 90 94 92 95 0
- 6 92 89 88 89 85 173
- 7 91 88 93 94 91 0
- 8 93 89 91 90 93 91
- 9 87 90 89 95 88 95
- 10 90 90 92 91 86 0
- sumar_despues_de_x <- function(datos, valor)
- {
- vec <- matrix(ncol = ncol(datos), nrow = nrow(datos)) #Predefino la matriz
- for (i in 2:ncol(df))
- {
- vec[,i] <- ifelse(datos[,i-1]==valor, datos[,i], NA) #Retengo sólo los valores posteriores a 89
- }
- rowSums(vec, na.rm = TRUE) #Saco un vector con las sumas de filas de la matriz filtrada
- }
- df$eval <- sumar_despues_de_x (df, 89)
- set.seed(2018)
- df <- data.frame(x1=sample(89:91, 10, replace = TRUE), #Aumento la probabilidad de 89
- x2=sample(85:95, 10),
- x3=sample(89:91, 10, replace = TRUE),
- x4=sample(90:100, 10))
- library(tidyverse)
- library(data.table) #para transpose()
- df %>%
- data.table::transpose() %>% #pq `purrr` tiene una función con el mismo nombre.
- gather() %>%
- group_by(key) %>%
- mutate(filtrado = ifelse(lag(value)==89, value, NA)) %>%
- summarise(suma_filtrada = sum(filtrado, na.rm = T)) %>%
- mutate(key = str_remove(key, "V")) %>%
- arrange(as.numeric(key)) %>%
- select(-key) %>%
- bind_cols(df, .)
- x1 x2 x3 x4 suma_filtrada
- 1 90 89 89 91 180
- 2 90 91 90 98 0
- 3 89 93 89 90 183
- 4 89 90 89 93 183
- 5 90 92 91 97 0
- 6 89 88 90 94 88
- 7 90 86 89 99 99
- 8 89 87 91 95 87
- 9 91 94 90 100 0
- 10 90 95 89 96 96
Add Comment
Please, Sign In to add comment