簡體   English   中英

根據另一個矩陣更改矩陣列中的名稱

[英]Change the names in the column of matrix according to the other matrix

讓我們舉個例子。 我有兩個矩陣:

名稱矩陣:

> dput(a)
structure(c("Greg", "Martin", "Hunge", "Rek", "Pred", "Singa", 
"Kreton", "Wita", "Marcus", "Sebas", "Theo", "Rox", "Plate", 
"Tret"), .Dim = c(7L, 2L))

數據矩陣:

> dput(b)
structure(c("Greg", "Hunge", "Pred", "12", "54", "11", "33", 
"44", "55", "61", "23", "68", "34", "123", "43", "22", "112", 
"35", "79", "22", "19"), .Dim = c(3L, 7L))

我想根據矩陣a更改數據矩陣(第一列)中的名稱。 因此,輸出應為:

> dput(c)
structure(c("Wita", "Sebas", "Rox", "12", "54", "11", "33", 
"44", "55", "61", "23", "68", "34", "123", "43", "22", "112", 
"35", "79", "22", "19"), .Dim = c(3L, 7L))

最簡單的方法是什么? 請記住,中a名字比我需要的更多。 功能需要為每行找到合適的名稱。

您可以為此使用match()

a <- structure(c("Greg", "Martin", "Hunge", "Rek", "Pred", "Singa", 
            "Kreton", "Wita", "Marcus", "Sebas", "Theo", "Rox", "Plate", 
            "Tret"), .Dim = c(7L, 2L))

b <- structure(c("Greg", "Hunge", "Pred", "12", "54", "11", "33", 
            "44", "55", "61", "23", "68", "34", "123", "43", "22", "112", 
            "35", "79", "22", "19"), .Dim = c(3L, 7L))

# copy
c <- b
c[ ,1] <- a[match(b[ ,1], a[ ,1]), 2]
c
#     [,1]    [,2] [,3] [,4] [,5]  [,6]  [,7]
#[1,] "Wita"  "12" "33" "61" "34"  "22"  "79"
#[2,] "Sebas" "54" "44" "23" "123" "112" "22"
#[3,] "Rox"   "11" "55" "68" "43"  "35"  "19"

我希望這對您有用...

d=merge(b,a,by.x=1,by.y=1)
c=as.matrix(d)
c=c[,-1]
c=c[,c(7,1:6)]
colnames(c)=NULL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM