'How to add a column in dataframes within a list with logical vector in R?

I would like to add a column in each dataframe within a list as logical after V1. Those columns should contain the information (TRUE/FALSE), if the value of V2 is between the range of 20 and 40.

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)


Solution 1:[1]

Maybe this is a possibility for you. I am going to consider the data you provided, but changed from tibble to data.frame. So, you can do:

mat1 <- matrix(sample(seq(-1,100, 0.11),50, replace = TRUE),ncol = 5) 
mat1 <- data.frame(mat1)

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

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


data <- list(mat1=mat1,mat2=mat2, mat3=mat3)

To add a column with the logical operation you want, you can use ifelse statement. Lets create a function with this statement and the logical:

if.logical<-function(data){
  ifelse (data>20 & data<40,TRUE,FALSE)
}

Now, since we have a list, we can run this function with for loop, which will create a new column with logical output on each dataframe. In your case i believe you wanted for the X2 column:

for (i in 1:length(data)){
  data[[paste0("mat",i)]]["LogiX2"]<-if.logical(data[[paste0("mat",i)]]$X2)
  }

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 BrunoPLC