如何用数字索引替换字符字符串

4

您如何用数字值替换字符串?

例如,假设我有一个向量:

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
  • Red 的索引为 5

1
如果您不关心索引值的顺序,则可以使用as.integer(factor(n)) - AshOfFire
4个回答

4

以下是使用保留所需顺序的factor方法的解决方案:

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

这是这个问题的最佳答案,而且符合 R 的惯用方式。 - Andre Elrico
这是我收到过的最好的评论,谢谢。 - Terru_theTerror

2
我们可以使用match
match(n, unique(n))
#[1] 1 1 1 2 3 3 4 4 4 4 5

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 

如果您想查看相应的名称


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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接