如果向量的值对应于(存在)数据框的列,我如何使用 dplyr 在 R 中检查它们?
How can I check in R using dplyr the values of a vector if they correspond (exist) to a column of a data frame?
假设我在 R 中有一个如下所示的数据框:
var1
lc
A
london
B
athens
C
amsterdam
D
new york
E
tokyo
F
barcelona
G
rome
H
mexico city
I
cairo
var1 = c("A","B","C","D","E","F","G","H","I")
lc = c("london","athens","amsterdam","new york","tokyo","barcelona","rome","mexico city","cairo")
df = tibble(var1,lc);df
现在我有一个感兴趣的矢量,其中包含一些我必须检查的值。
var2 = c("A","C","E","F","G","H","I","J","K","L","M")
我感兴趣的条件是,如果列向量var1的元素存在于第二个向量(var2)中。
理想情况下,想要改变(dplyr 短语)一个新列,如果这个逻辑条件必须包含输出,并且必须看起来像这样。
var1
lc
condition
A
London
TRUE
B
athens
FALSE
C
amsterdam
TRUE
D
new york
FALSE
E
tokyo
TRUE
F
barcelona
TRUE
G
rome
TRUE
H
mexico city
TRUE
I
cairo
TRUE
我如何在 R 中使用 dplyr 做到这一点?
有帮助吗?
您可以使用 %in%
df %>% mutate(condition = var1 %in% var2)
假设我在 R 中有一个如下所示的数据框:
var1 | lc |
---|---|
A | london |
B | athens |
C | amsterdam |
D | new york |
E | tokyo |
F | barcelona |
G | rome |
H | mexico city |
I | cairo |
var1 = c("A","B","C","D","E","F","G","H","I")
lc = c("london","athens","amsterdam","new york","tokyo","barcelona","rome","mexico city","cairo")
df = tibble(var1,lc);df
现在我有一个感兴趣的矢量,其中包含一些我必须检查的值。
var2 = c("A","C","E","F","G","H","I","J","K","L","M")
我感兴趣的条件是,如果列向量var1的元素存在于第二个向量(var2)中。
理想情况下,想要改变(dplyr 短语)一个新列,如果这个逻辑条件必须包含输出,并且必须看起来像这样。
var1 | lc | condition |
---|---|---|
A | London | TRUE |
B | athens | FALSE |
C | amsterdam | TRUE |
D | new york | FALSE |
E | tokyo | TRUE |
F | barcelona | TRUE |
G | rome | TRUE |
H | mexico city | TRUE |
I | cairo | TRUE |
我如何在 R 中使用 dplyr 做到这一点? 有帮助吗?
您可以使用 %in%
df %>% mutate(condition = var1 %in% var2)