[英]Output column index based on each row in data.frame
我有一個data.frame
Orig <- c("HKG", "PEK", "PVG", "AMS")
stop2 <- c("", "HKG", "PEK", "HKG")
stop3 <- c("", "", "HKG", "")
Dest <- "X"
(data <- data.frame(Orig, stop2, stop3, Dest))
Orig stop2 stop3 Dest
1 HKG X
2 PEK HKG X
3 PVG PEK HKG X
4 AMS HKG X
對於每一行,我想輸出出現HKG的列索引。 例如,對於第二行,“ HKG”位於第二列stop2。 因此,我希望輸出為2。
所需的輸出是這樣的:
Orig stop2 stop3 Dest output
1 HKG X 1
2 PEK HKG X 2
3 PVG PEK HKG X 3
4 AMS HKG X 2
我最初的想法是使用which(=="HKG")
,但是我只知道如何使用colnames
。
您可以使用which
連同t
,雖然@thelatemail的回答是更直觀:
dat$output <- which(t(dat) == "HKG", arr.ind=TRUE)[,1]
# This next line does the same thing, and is perhaps more clear than using [,1]:
# dat$output <- which(t(dat) == "HKG", arr.ind=TRUE)[,"row"]
dat
# Orig stop2 stop3 Dest output
#1 HKG X 1
#2 PEK HKG X 2
#3 PVG PEK HKG X 3
#4 AMS HKG X 2
apply
於每一行:
dat$output <- apply(dat[,-4],1,function(x) which(x=="HKG") )
或者,如果速度很重要,請嘗試以下方法,它將快20倍。
intm <- dat[-4]=="HKG"
dat$output <- col(intm)[intm][order(row(intm)[intm])]
甚至更簡單:
max.col(dat[-4]=="HKG")
全部導致:
# Orig stop2 stop3 Dest output
#1 HKG X 1
#2 PEK HKG X 2
#3 PVG PEK HKG X 3
#4 AMS HKG X 2
indx <- (t(dat)=="HKG")*(seq_len(nrow(dat)))
indx[!!indx]
#[1] 1 2 3 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.