基于R上的矩阵翻译矢量

时间:2014-06-26 07:26:00

标签: r

我有一个指示矩阵,如下所示:

John   1
Ann   2
Ruby   3
Clair   4

所以我想将这个向量翻译为保持顺序的数字,如下所示:

(John,Ann,John,Clair,John,Ruby,Ann,John,Ruby)->(1,2,1,4,1,3,2,1,3)

我不知道如何用R(没有循环)。

请帮帮我。 THKS

5 个答案:

答案 0 :(得分:2)

您可以使用factor,请参阅使用?factor的文档。

x <- c('John','Ann','John','Clair','John','Ruby','Ann','John','Ruby')
y <- factor(x, levels = c("John", "Ann", "Ruby", "Clair"))

as.numeric(y)
## [1] 1 2 1 4 1 3 2 1 3

希望它有所帮助,

亚历

答案 1 :(得分:0)

x <- c('A','B','A','D','A','C','B','A','C')
y <- match(x, LETTERS)

source

[编辑] 修改后考虑了Shadow的评论

答案 2 :(得分:0)

即使在更新的示例中,您也可以像@Pascal描述的那样使用?match。不要与LETTERS匹配。

# generate example
df <- data.frame(input=c("John", "Ann", "Ruby", "Clair"), 
                 output=1:4)
x <- c("John", "Ann", "John", "Clair", "John", 
       "Ruby", "Ann", "John", "Ruby")
# 
# if output is indeed just 1:nrow(df)
match(x, df[, "input"])
# if output is different
df[match(x, df[, "input"]), "output"]

答案 3 :(得分:0)

@Shadow的另一种方法:

library(doBy)

x <- c('John','Ann','John','Clair','John','Ruby','Ann','John','Ruby')
src <- c('John', 'Ann', 'Ruby', 'Clair')
tgt <- c(1,2,3,4)

x <- recodeVar(x, src, tgt)
x <- as.numeric(x)   

答案 4 :(得分:0)

你也可以这样做:

 df <- data.frame(input=c("John", "Ann", "Ruby", "Clair"), 
             output=1:4,stringsAsFactors=F) #should work with factors also
 x <- c("John", "Ann", "John", "Clair", "John", 
   "Ruby", "Ann", "John", "Ruby")
 with(df, setNames(output, input))[x]
 #John   Ann  John Clair  John  Ruby   Ann  John  Ruby 
 # 1     2     1     4     1     3     2     1     3 

如果您不需要姓名

 as.vector(with(df, setNames(output,input))[x])
 #[1] 1 2 1 4 1 3 2 1 3