【发布时间】:2021-10-10 19:03:02
【问题描述】:
我有一个包含两列 T 和 F 的数据框。 我想知道
- 第一行是T,第二行是F
- 第一行是F,第二行是T
- 哪一行都是F
我对这件事几乎没有什么线索,有人能指点一下吗?
【问题讨论】:
标签: r dataframe logical-operators
我有一个包含两列 T 和 F 的数据框。 我想知道
我对这件事几乎没有什么线索,有人能指点一下吗?
【问题讨论】:
标签: r dataframe logical-operators
你可以使用case when
library(dplyr)
df = data.frame(x = c("T","T","F","F","F"), y = c("T","F","T","F","X"))
df %>%
mutate(condition = case_when(
x == "T" & y == "T" ~ "Both are T",
x == "T" & y == "F" ~ "First is T fecond is F",
x == "F" & y == "F" ~ "Both are F",
x == "F" & y == "T" ~ "First is F, second is T",
TRUE ~ "Something else"
))
#> x y condition
#> 1 T T Both are T
#> 2 T F First is T fecond is F
#> 3 F T First is F, second is T
#> 4 F F Both are F
#> 5 F X Something else
由reprex package (v2.0.0) 于 2021-08-05 创建
【讨论】:
这是解决问题的一种可能方法:
library(dplyr)
df <- data.frame(a = rep(c(T, F, T, F), each=2),
b = rep(c(T, T, F, F), each=2))
# a b
# 1 TRUE TRUE
# 2 TRUE TRUE
# 3 FALSE TRUE
# 4 FALSE TRUE
# 5 TRUE FALSE
# 6 TRUE FALSE
# 7 FALSE FALSE
# 8 FALSE FALSE
df %>%
mutate(newcol = case_when(a & !b ~ "first=T second=F",
!a & b ~ "first=F second=T",
!a & !b ~ "both=F",
TRUE ~ "other"))
# a b newcol
# 1 TRUE TRUE other
# 2 TRUE TRUE other
# 3 FALSE TRUE first=F second=T
# 4 FALSE TRUE first=F second=T
# 5 TRUE FALSE first=T second=F
# 6 TRUE FALSE first=T second=F
# 7 FALSE FALSE both=F
# 8 FALSE FALSE both=F
【讨论】:
您可以将 [a,b] 列视为 2 位二进制数向量,并将 a*2+b 将其从二进制转换为十进制。因此,2*a+b+1 映射到 1,2,3,4。
试试下面的基本 R 代码
transform(
df,
newcol = c("both=F", "first=F,second=T", "first=T,second=F", "other")[a * 2 + b + 1]
)
给了
a b newcol
1 TRUE TRUE other
2 TRUE TRUE other
3 FALSE TRUE first=F,second=T
4 FALSE TRUE first=F,second=T
5 TRUE FALSE first=T,second=F
6 TRUE FALSE first=T,second=F
7 FALSE FALSE both=F
8 FALSE FALSE both=F
df <- data.frame(a = rep(c(T, F, T, F), each=2),
b = rep(c(T, T, F, F), each=2))
【讨论】:
[a * 2 + b + 1] 部分的作用或它是如何工作的。我收集这些是列名,但操作逻辑仍然让我感到困惑。
[a,b] 列视为2 位二进制数向量,a*2+b 将其从二进制转换为十进制。在这种情况下,2*a+b+1 映射到 1,2,3,4。