将“ x1”,“ x2”,“ x3”与“目标”进行比较,如何返回与“目标”匹配的列的 first 索引?不适用将导致不适用。
pop <- c("A", "B", "C", "D")
target <- pop
x1 <- sample(pop)
x2 <- sample(pop)
x3 <- sample(pop)
df <- data.frame(target,x1,x2,x3)
> df
target x1 x2 x3
1 A B B D
2 B D C C
3 C C A A
4 D A D B
我尝试使用以下方式:
min(which(df[3, 1] == df[3, 2:ncol(df)]))
...(以第3行为例),但是我不知道如何优雅地处理没有匹配项的情况,这可能就是为什么我无法在apply()函数中使用它的原因。目标是df上的新列或返回值的向量。
谢谢!
答案 0 :(得分:1)
有很多方法可以做到这一点。遍历第2:4列,与target
比较,并与which
sapply(df[-1], function(x) which(x == df$target)[1])
x1 x2 x3
#1 3 NA
如果用于比较行
m1 <- df$target == df[-1]
max.col(m1, 'first') * NA^!rowSums(m1)
或
apply(m1, 1, function(x) which(x)[1])
df <- data.frame(target,x1,x2,x3, stringsAsFactors = FALSE)
答案 1 :(得分:1)
这是使用match
-
> df
target x1 x2 x3
1 A C A C
2 B A B B
3 C D D D
4 D B C A
apply(df, 1, function(x) match(TRUE, x[-1] == x[1]))
[1] 2 2 NA NA
数据-
df <- structure(list(target = c("A", "B", "C", "D"), x1 = c("C", "A",
"D", "B"), x2 = c("A", "B", "D", "C"), x3 = c("C", "B", "D",
"A")), .Names = c("target", "x1", "x2", "x3"), row.names = c(NA,
-4L), class = "data.frame")