我有一列带有长字符串,所以我想将其转换为R中的简单整数,以便我可以轻松地将该列与其他表连接起来

时间:2018-11-08 03:56:55

标签: r indexing hash

我在具有长字符串的数据集中有一列,我想将R中的特定列转换为简单的整数值(散列或索引),以便我可以轻松地将其他表与该特定列联接,任何人都可以提出建议这个吗?

library(tidyverse)
mpg

mpg <- mpg %>% mutate(displ = as.character(displ), year = 
as.character(year)) %>%
mutate(matcher = as.character(paste(model, displ, year, sep = ""))) 


View(mpg)

如果看到matcher列,它具有一个长字符串值作为字符向量,我想将这些值映射到简单整数,例如1、2、3等。我该怎么办?

1 个答案:

答案 0 :(得分:0)

如果您只想捕获每个唯一的字符串并为其分配一个数字,则可以这样做。如果您描述了更复杂的映射,我将编辑答案:

> z <- transform(mpg, matchnum=as.integer(factor(matcher, unique(matcher))))
> head(z)
  manufacturer model displ year cyl      trans drv cty hwy fl   class   matcher matchnum
1         audi    a4   1.8 1999   4   auto(l5)   f  18  29  p compact a41.81999        1
2         audi    a4   1.8 1999   4 manual(m5)   f  21  29  p compact a41.81999        1
3         audi    a4     2 2008   4 manual(m6)   f  20  31  p compact   a422008        2
4         audi    a4     2 2008   4   auto(av)   f  21  30  p compact   a422008        2
5         audi    a4   2.8 1999   6   auto(l5)   f  16  26  p compact a42.81999        3
6         audi    a4   2.8 1999   6 manual(m5)   f  18  26  p compact a42.81999        3