【问题标题】:Combine several boolean variables in a data frame in R using a logical or [duplicate]使用逻辑或 [重复] 在 R 中的数据框中组合几个布尔变量
【发布时间】:2019-05-11 22:13:10
【问题描述】:

使用逻辑或组合数据框中的多个布尔变量 我有一个数据框,其中包含我试图组合的几个布尔变量。

这是一个示例数据集:

     temp1 temp2 temp3
[1,] FALSE FALSE FALSE
[2,]  TRUE  TRUE FALSE
[3,] FALSE  TRUE  TRUE
[4,]  TRUE  TRUE  TRUE
[5,]  TRUE  TRUE FALSE
[6,]  TRUE FALSE FALSE

我想添加第四个变量“temp4”,如果 temp1 OR temp2 OR temp3 为 TRUE,则该变量为 TRUE。我试过这个:

temp$temp3<-any(temp1,temp2)

但它会将其强制转换为列表并创建一个奇怪的输出。

我找到的最接近的是:Combine logical vectors in list using logical or

但这是一个列表,而不是数据框,我不熟悉列表,不知道如何将它应用于我的问题。

谢谢

【问题讨论】:

  • Reduce(`|`, temp) 假设 temp 实际上是 data.frame 而不是 matrix 就像在您的示例中那样。

标签: r dataframe boolean


【解决方案1】:

使用应用循环。例如:

temp4 <- apply(temp, 1, any)
cbind(temp, temp4)

【讨论】:

  • 太好了,这行得通。如果我想选择使用的列怎么办?假设我想要一个当 temp1 或 temp3 为 TRUE 时为 TRUE 的变量 temp5。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 2020-06-09
  • 2019-10-15
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多