R中的'which'函数返回row = 1而匹配值是否在第2行?

问题描述 投票:0回答:2

我有一个翻译表,我正在使用do.call(paste, input) %in% do.call(paste, big_translation_table)

它返回TRUEFALSE

然后我使用which函数来查找索引,但它总是返回1

请指教。

这是一个小例子:

test1 <- data.frame(a = 1, b=2, c = "r", stringsAsFactors = FALSE)
test2 <- data.frame(a = c(1,2), b=c(2,10), c = c("r","p"), stringsAsFactors = FALSE)

which(do.call(paste, test1) %in% do.call(paste, test2))

返回1,没关系,现在让我们测试一下:

test1 <- data.frame(a = 2, b=10, c = "p", stringsAsFactors = FALSE)
which(do.call(paste, test1) %in% do.call(paste, test2))

也返回1。我认为它应该返回2。

请指教。

r dataframe pattern-matching which
2个回答
3
投票

%in%只是(在这种情况下)test1是否出现在test2的逻辑测试,而不是根据具体情况。我想你只想要==

test1 <- data.frame(a = 1, b=2, c = "r", stringsAsFactors = FALSE)
> which(do.call(paste, test1) == do.call(paste, test2))
[1] 1

然后:

test1 <- data.frame(a = 2, b=10, c = "p", stringsAsFactors = FALSE)
> which(do.call(paste, test1) == do.call(paste, test2))
[1] 2

0
投票

OP要求在翻译表test2中找到所有列中匹配的行号。他将所有专栏粘贴在一起,为查找test1中的test2创造了一个自然的关键。

不是将列重复粘贴在一起,而是进行连接更有效。 data.table包有which参数,它返回行号:

library(data.table)
setDT(test2)[setDT(test1), on = names(test1), which = TRUE]
[1] 2

对于第二个测试用例。

如果有必要明确要在连接中使用的列,我们可以写

setDT(test2)[setDT(test1), on = .(a, b, c), which = TRUE]
© www.soinside.com 2019 - 2024. All rights reserved.