我有以下数据框,我想用其值与列“Item”匹配的列的名称填充列“TargetPos”(在这种情况下为“Left”)(在我的实际数据中,我实际上有四个位置:TopRight、TopLeft、BottomRight、BottomLeft)。可以使用什么方法?
我一直在尝试以下方法:
df$TargetPos <- lapply(df$Item, function(x)
if (x == df$Right) {
names(df$Right)
} else {
Left
})
最佳答案
既然你想有矢量作为输出,你应该使用 sapply
而不是 lapply
。
解决方案的核心是使用 which
输出具有与 Item
列匹配的值的列索引(记住 + 1
,因为索引时不包括 Item
列本身),并输出 colnames
。
为了演示目的,我创建了一些额外的行。
df <- data.frame(Item = c("bed.png", "a", "b", "e", "532523"),
Right = c("flag.png", "a", "c", "e", "aaa"),
Left = c("bed.png", "b", "b", "e", "bbb"))
Item Right Left
1 bed.png flag.png bed.png
2 a a b
3 b c b
4 e e e
5 532523 aaa bbb
df$TargetPos <-
sapply(1:nrow(df),
function(x) colnames(df)[which(df[x, -1] == df$Item[x]) + 1])
df
Item Right Left TargetPos
1 bed.png flag.png bed.png Left
2 a a b Right
3 b c b Left
4 e e e Right, Left
5 532523 aaa bbb
https://stackoverflow.com/questions/71726392/