2015-11-15 93 views
0

我想在一个向量中更改列中的一些变量的名称,这些变量同时存在于列中。我知道我可以用数据集中的每个值来完成此操作,但这需要数小时。更改列中值的名称R

我有这样的数据集:

df=data.frame(species = c("yo.manhereisareallllllylongname", 
         "heydude.this.is.realllylong", 
         "sooooooo.long", 
         "what.whatshouldIdo", 
         "what.whatshouldIdo", 
         "shouldIstayorshouldIgo", 
         "sooooooo.long"), 
      site = c("site1","site2","site3","site4","site5","site6","site7")) 

是这样的:

      species site 
1 yo.manhereisareallllllylongname site1 
2  heydude.this.is.realllylong site2 
3     sooooooo.long site3 
4    what.whatshouldIdo site4 
5    what.whatshouldIdo site5 
6   shouldIstayorshouldIgo site6 
7     sooooooo.long site7 

我要创建这个载体(在这里你可以看到,我没有在原始数据集重复的对象,它们是唯一的。):

short_names=c("ymrln","heydude","slong","wwsid", "sisosig") 

这对应于此:

long_names=c("yo.manhereisareallllllylongname","heydude.this.is.realllylong","sooooooo.long","what.whatshouldIdo","shouldIstayorshouldIgo") 

最终的结果是:

species site 
1 ymrln site1 
2 heydude site2 
3 slong site3 
4 wwsid site4 
5 wwsid site5 
6 sisosig site6 
7 slong site7 

你有一个快速的方法来做到这一点?这是一种数据集中的查找和替换功能,而不是在脚本中。

感谢,

+2

一种标准方式:'short_names [match(df $ species,long_names)]' – Frank

回答

3

您可以在plyr包mapvalues功能做到这一点。

library(plyr) 
df$species <- mapvalues(df$species, long_names, short_names) 
+0

非常感谢! –

2

试试这个。

match_df <- data.frame(short_names, long_names) 
df$species <- match_df$short_names[df2$species] 

head(df) 
# species site 
#1 sisosig site1 
#2 ymrln site2 
#3 slong site3 
#4 wwsid site4 
#5 wwsid site5 
#6 heydude site6 
3

我们也可以使用loopuplibrary(qdapTools)

library(qdapTools) 
df$species <- lookup(df$species, data.frame(long_names, short_names)) 

df 
# species site 
#1 ymrln site1 
#2 heydude site2 
#3 slong site3 
#4 wwsid site4 
#5 wwsid site5 
#6 sisosig site6 
#7 slong site7 

根据?lookup

查找-data.table基于哈希表的大载体查找有用。