[英]Finding matching values in two vectors of different lengths in R
我有兩個帶有物種名稱的向量,它們遵循兩種不同的方法。 有些名稱相同,有些名稱不同,並且兩者的排序方式不同。 一個例子:列表 1: c(Homo sapiens sapiens, Homo sapiens neanderthalensis, Homo直立人,...,n) 列表 2: c(Homo直立人, Homo sapiens, Homo neanderthalensis,...,n+1)
我寫 n 和 n+1 來表示這些列表有不同的長度。
我想創建一個由兩個值組成的新列表:在兩個向量(例如直立人)之間存在匹配的情況下,我希望列表 2 的名稱位於列表中名稱所在的位置1,或者如果列表 1 中的位置不匹配“0”。所以在這種情況下,這個新列表將是 newlist: c(0,0, Homo直立人,...)
為此,我編寫了以下代碼,但它不起作用。
data<-read.table("species.txt",sep="\t",header=TRUE)
list1<-as.vector(data$Species1)
list2<-as.vector(data$Species2)
newlist<-as.character(rep(0,length(list1)))
for (i in 1:length(list1)){
for (j in 1:length(list2)){
if(list1[i] == list2[j]){newlist[i]<- list2[j]}else {newlist[i]= 0}
}
}
我希望這很清楚。
謝謝你的幫助!
以這個可重現的例子為例:
set.seed(1)
list1 <- letters[1:10]
list1names
list2 <- letters[sample(1:10, 10)]
您可以使用ifelse
避免循環:
newlist <- ifelse(list1==list2, list2, 0)
問題是你沒有聲明newname
,你的意思是newlist
嗎?
如果要使用循環,則只能使用一個循環而不是 2 個循環,因為length(list1)
= length(list2)
:
for (i in 1:length(list1)){
if(list1[i] == list2[i]){newlist[i]<- list2[i]}else {newlist[i]= 0}
}
一般來說,如果你想匹配向量中的元素,你可以像這樣使用match
:
> list1
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
> list2
[1] "c" "d" "e" "g" "b" "h" "i" "f" "j" "a"
> match(list1, list2)
[1] 10 5 1 2 3 8 4 6 7 9
如您所見, match
獲取list2
中元素的索引,這些索引等於list1
的元素。 如果您有另一個表data2
,並且您想從data2$list3
data$list1 中獲取對應元素的 data2 中的列,這很有用,您可以使用:
data <- data.frame(list1, list2)
list3 <- list2
columntoget <- 1:length(list2)
data2 <- data.frame(list3, columntoget)
data$mynewcolumn <- data2$columntoget[match(data$list1, data2$list3)]
> data$mynewcolumn
[1] 10 5 1 2 3 8 4 6 7 9
我不完全確定我了解您想要實現的目標,但我認為這可以滿足您的需求。
list1 <- c("Homo sapiens sapiens","Homo sapiens neanderthalensis","Homo erectus")
list2 <- c("Homo erectus","Homo sapiens","Homo neanderthalensis")
sapply(list1, function(x) { ifelse(x %in% list2, list2[which(list1 == x)], 0) } )
內部 for 循環使用newname[i]
,它應該是newlist[i]
。 使用您的代碼,您可以使用0
或物種名稱覆蓋newlist[i]
條目j
次。 這可能不是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.