我正在尝试根据另一个表中的值为一个表创建一个新的标志变量(二进制)。我环顾了stackoverflow,但似乎找不到类似的问题。 例如,我有表A和表B,它们每个都有变量customer。
表A:
A.customer
1
2
3
4
5
表B:
B.customer
1
2
6
我想在A中创建一个称为变量的新变量,如果客户中的值也出现在B中,则flag = Y,否则flag = N。 像这样:
A.customer A.flag
1 Y
2 Y
3 N
4 N
5 N
我可以通过哪些方式联接表并设置新的变量标志?任何帮助表示赞赏。
答案 0 :(得分:2)
使用%in%
运算符
A = 1:5
B = c(1,2,6)
> A %in% B
[1] TRUE TRUE FALSE FALSE FALSE
答案 1 :(得分:0)
要创建新列,请使用%in%
和factor
。
A.flag <- TableA$A.customer %in% TableB$B.customer
TableA$A.flag <- factor(A.flag, labels = c("N", "Y"))
TableA
# A.customer A.flag
#1 1 Y
#2 2 Y
#3 3 N
#4 4 N
#5 5 N
数据。
TableA <-
structure(list(A.customer = 1:5, A.flag = structure(c(2L, 2L,
1L, 1L, 1L), .Label = c("N", "Y"), class = "factor")), row.names = c(NA,
-5L), class = "data.frame")
TableB <-
structure(list(B.customer = c(1L, 2L, 6L)), class = "data.frame", row.names = c(NA,
-3L))
答案 2 :(得分:0)
使用tidyverse,您可以像这样使用case_when
:
decimal slno = 2696709;
string result = Math.Round((slno / 256), 0).ToString() +
Math.Ceiling(((slno / 256) -
Math.Round((slno / 256), 0) * 256)).ToString();
由reprex package(v0.2.1)于2018-10-31创建
library(tidyverse)
table_a <- data_frame(A.customer = 1:5)
table_b <- data_frame(B.customer = c(1, 2, 6))
table_a
#> # A tibble: 5 x 1
#> A.customer
#> <int>
#> 1 1
#> 2 2
#> 3 3
#> 4 4
#> 5 5
table_b
#> # A tibble: 3 x 1
#> B.customer
#> <dbl>
#> 1 1
#> 2 2
#> 3 6
table_a %>%
mutate(
A.flag = case_when(
A.customer %in% table_b$B.customer ~ "Y",
TRUE ~ "N"
)
)
#> # A tibble: 5 x 2
#> A.customer A.flag
#> <int> <chr>
#> 1 1 Y
#> 2 2 Y
#> 3 3 N
#> 4 4 N
#> 5 5 N
的作用类似于if / else if / else。因此,您说“如果A.customer在case_when
中,则返回值table_b$B.customer
。”然后“在所有其他情况下(否则Y
始终为TRUE)将返回TRUE
。”