2016-10-04 98 views
0

最佳R,在data.frame通过从另一个data.frame值+动态列

基本上,我有一个表数据和一个较小的表词汇替换值。 我想有是,该词汇数值很好地对数据值映射。而这一功能中,以这样一种方式,它可以被用来+/- dynamicaly

考虑:

dt : data.csv 
V1____V2___sex__V4__V5_ 
abc abc jeny abc 123 
abc abc eric abc 123 
abc abc bob abc 123 

vocabulary1: sex.csv 
old___new 
jeny f 
eric m 
bob m 

通缉的结果:

V1____V2___sex__V4__V5_ 
abc abc f abc 123 
abc abc m abc 123 
abc abc m abc 123 

我”什么已经

replace_by_vocabulary <- function(dt,voc,col_name){ 
    dt[,col_name] <- tolower(dt[,col_name]) 

    **** something something *** 

    return(dt) 
} 

我怎么想使用它...

dt <- replace_by_vocabulary(dt,vocabulary1,"sex") 
dt <- replace_by_vocabulary(dt,vocabulary2,"date") 
dt <- replace_by_vocabulary(dt,vocabulary3,"mood") 
+3

[R中VLOOKUP类型的方法](http://stackoverflow.com/questions/18645222/vlookup-type-method-in-r) –

回答

2

merge的替代方案,是更符合你有什么:

replace_by_vocabulary <- function(dt,voc,col_name){ 
    col <- which(colnames(dt) == col_name) 
    dt[,col] <- voc$new[match(tolower(dt[,col]), voc$old)] 
    return(dt) 
} 

您想要首先从col_name字符串输入中找到dt中的列。然后,使用match查找与tolower(dt[,col])匹配的行索引voc$old,并使用这些索引从voc$new检索替换值。在这里,我们将dt[,col]列转换为全部小写字母,就像您在示例代码中那样,在函数中动态地进行匹配,以匹配词汇表中的小写字母数据。与merge相比,其优势在于我们不必重新命名并删除列以获取所需的结果。

使用您的数据:

replace_by_vocabulary(dt,vocabulary,"sex") 
## V1 V2 sex V4 V5 
##1 abc abc f abc 123 
##2 abc abc m abc 123 
##3 abc abc m abc 123 
1

你有没有考虑合并,然后丢弃不需要的列?像这样。

dt<-merge(x=dt, y=vocabulary1, by.x="sex", by.y="old") 
dt<-dt %>% 
    select(-sex) %>% 
    mutate(sex=old) 
1

这篇文章似乎是下面列出的副本。

VLookup type method in R

你应该能够制定出一个功能做你想要使用合并功能做什么:

string = c("abc", "abc", "abc") 
names = c("jeny", "eric", "bob") 
sex = c("f", "m", "m") 

data = data.frame(cbind(string, string, names, string, c(1, 2, 3))) 
vocabulary1 = data.frame(cbind(names, sex)) 

dt = merge(data, vocabulary1, by.x = "names") 
dt 
1

如果我明白你的目标是正确的要合并两个数据。帧在一起? 你应该看看?merge

例如:

merge(x = dt, y = vocabulary1, by.x = "sex", by.y = "old") 

如果你想有一个动态的功能,你可以做

replace_by_vocabulary <- function(dt,voc,col_name){ 
    merged_df <- merge(x = dt, y = voc, by.x = "sex", by.y = col_name) 
    return(merged_df) 
} 
+0

没有可能的复制,目标是如果它们与词表中的“旧”列匹配,则替换一列中的值。但你不能做类似dt $ [“sex”] == voc $ old < - voc $ new。或什么 – Dieter

+0

然后,我认为@aichao提供了一个很好的解决方案,你可以接受。 –