data.table: 查找唯一 ID 与向量中的元素匹配的次数
data.table: find number of times unique id matches element in vector
我正在寻找 data.table 这个问题的解决方案。我有这样的数据:
library(data.table)
codes1 <- c("A1", "A2", "A3")
codes2 <- c("B1", "B2", "B3")
codes3 <- c("C1", "C2", "C3")
data <- data.table(
id = c(1,1,2,3,3,4,4,4),
code = c("A1","A3", "B1", "A2", "B2","A1","B2","C1")
)
我想为每个唯一 ID 计算 data$code
与向量 codes1
、codes2
和 codes3
中的元素匹配的次数,只计算一次对于每个向量中的匹配项。我希望得到以下结果:
data_want <- data.table(
id = c(1,2,3,4),
match = c(1,1,2,3)
)
将codes
向量放在list
中,用[=15=循环遍历list
,按'id'分组后,检查是否[= any
的元素是%in%
的'code'列,Reduce
的list
的逻辑向量通过加上(+
- TRUE
-> 1 和 FALSE
-> 0)
library(data.table)
data[, .(match = Reduce(`+`, lapply(list(codes1, codes2, codes3),
\(x) any(x %in% code)))), by = id]
-输出
id match
<num> <int>
1: 1 1
2: 2 1
3: 3 2
4: 4 3
我正在寻找 data.table 这个问题的解决方案。我有这样的数据:
library(data.table)
codes1 <- c("A1", "A2", "A3")
codes2 <- c("B1", "B2", "B3")
codes3 <- c("C1", "C2", "C3")
data <- data.table(
id = c(1,1,2,3,3,4,4,4),
code = c("A1","A3", "B1", "A2", "B2","A1","B2","C1")
)
我想为每个唯一 ID 计算 data$code
与向量 codes1
、codes2
和 codes3
中的元素匹配的次数,只计算一次对于每个向量中的匹配项。我希望得到以下结果:
data_want <- data.table(
id = c(1,2,3,4),
match = c(1,1,2,3)
)
将codes
向量放在list
中,用[=15=循环遍历list
,按'id'分组后,检查是否[= any
的元素是%in%
的'code'列,Reduce
的list
的逻辑向量通过加上(+
- TRUE
-> 1 和 FALSE
-> 0)
library(data.table)
data[, .(match = Reduce(`+`, lapply(list(codes1, codes2, codes3),
\(x) any(x %in% code)))), by = id]
-输出
id match
<num> <int>
1: 1 1
2: 2 1
3: 3 2
4: 4 3