如何用数字索引替换字符纵梁

时间:2018-04-24 08:13:28

标签: r string

如何用数值替换字符串?

例如,假设我有一个这样的矢量,

n <- c(rep("Sam", 3), "Harry", rep("Sparky", 2), rep("Ted", 4), "Red")

>n
 [1] "Sam"    "Sam"    "Sam"    "Harry"  "Sparky" "Sparky" "Ted"    "Ted"    "Ted"   
[10] "Ted"    "Red"

我想获得这样的输出,

 [1] 1 1 1 2 3 3 4 4 4 4 5

哪里

  • Sam已被1
  • 编入索引
  • Harry已被2
  • 编入索引
  • Sparky 3
  • Ted 4
  • {li> Red 5

4 个答案:

答案 0 :(得分:4)

此处使用factor方法保留所需顺序的解决方案:

n <- factor(n, levels = unique(n))
> as.numeric(n)
 [1] 1 1 1 2 3 3 4 4 4 4 5

答案 1 :(得分:2)

我们可以使用match

match(n, unique(n))
#[1] 1 1 1 2 3 3 4 4 4 4 5

答案 2 :(得分:1)

这也可以:

as.numeric(sapply(n,function(x) grep(x,unique(n))))
[1] 1 1 1 2 3 3 4 4 4 4 5

sapply(n,function(x) grep(x,unique(n)))
 Sam    Sam    Sam  Harry Sparky Sparky    Ted    Ted    Ted    Ted    Red 
     1      1      1      2      3      3      4      4      4      4      5 

如果您想查看相应的名称

答案 3 :(得分:0)

如果有人想要更通用的方法:

id_matrix <- paste0(unique(n),"'s randomID")
names(id_matrix) <- unique(n)

给出:

# Sam               Harry              Sparky                 Ted                 Red 
#"Sam's randomID"  "Harry's randomID" "Sparky's randomID"    "Ted's randomID"    "Red's randomID" 

然后替换:

unname(id_matrix[n])

给出:

#[1] "Sam's randomID"    "Sam's randomID"    "Sam's randomID"    "Harry's randomID"  "Sparky's randomID" "Sparky's randomID" "Ted's randomID"   
#[8] "Ted's randomID"    "Ted's randomID"    "Ted's randomID"    "Red's randomID"    "Sam's randomID"

数据:

n <- c(rep("Sam", 3), "Harry", rep("Sparky", 2), rep("Ted", 4), "Red","Sam")