'How to add a new column in dataframes within a list and count the logical number to create a marker in R?

I would like to know how often the same logical expression shows up continously in dataframes within a list until it's changing and after showing up the first time for three or more than three times consecutively (= marker), cut off every data before and create a new dataframes within a list with the following 4 rows and cut again. That my final dataframes within this list all include dataframes with 4 rows.

library(dplyr)
set.seed(94756)
mat1 <- matrix(sample(seq(-1,100, 0.11),50, replace = TRUE),ncol = 5) 
mat1 <- as.tibble(mat1)

mat2 <- matrix(sample(seq(-1,100, 0.11),50, replace = TRUE),ncol = 5)  
mat2 <- as.tibble(mat2)

mat3 <- matrix(sample(seq(-1,100, 0.11), 50,replace = TRUE),ncol = 5)  
mat3 <- as.tibble(mat3)

data <- list(mat1, mat2, mat3)
data1 <- map(data, ~add_column(., V1_logical = between(.$V2, 20, 60), .after = 'V1'))

r_pre <- lapply(data1, "[", 2)

Find out the length of each logical: That in the end I have new dataframes within a list with

$logical = TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE ...
$length = 2, 1, 3 (=marker), 2, 1, 3, 7...

Set new dataframe:

$logical = FALSE, TRUE, FALSE, TRUE ...
$length = 2,1,3,7 (4 values)

It would be the following code without list for just one mat:

mat1 <- as.data.frame(mat1)
mat1 <- add_column(mat1, Filter = mat1$V1 > 20 & mat1$V1 < 60, .after = "V1")
r <- rle(mat1$Filter)
test <- data.frame(values = r$values, lengths = r$lengths)
test$ID <- 1:nrow(test)

marker <- as.numeric((min(which(test$values == TRUE & test$lengths >= 3))))

data_drop <- test[c(1:marker),]
data_drop_c <- as.numeric(sum(data_drop$lengths))
final_df <- mat1[-c(1:data_drop_c), ]

Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source