简体   繁体   English

如何在 R 的逻辑向量列表中的数据框中添加一列?

[英]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.我想在列表中的每个 dataframe 中添加一列作为 V1 之后的逻辑。 Those columns should contain the information (TRUE/FALSE), if the value of V2 is between the range of 20 and 40.如果 V2 的值介于 20 和 40 之间,则这些列应包含信息 (TRUE/FALSE)。

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)

Maybe this is a possibility for you.也许这对你来说是一种可能性。 I am going to consider the data you provided, but changed from tibble to data.frame.我将考虑您提供的数据,但从 tibble 更改为 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.要添加具有所需逻辑操作的列,可以使用 ifelse 语句。 Lets create a function with this statement and the logical:让我们用这个语句和逻辑创建一个 function:

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 循环运行这个 function,这将在每个 dataframe 上创建一个逻辑为 output 的新列。在你的情况下,我相信你想要 X2 列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM