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

杰米玛·杰亚库玛

我在带有长字符串的数据集中有一列,我想将特定列转换为 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 等。我怎样才能做到这一点?

神秘

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

> 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档