2016-10-26 38 views
3

(我一直坚持这个问题这两天,所以,如果有一个答案,所以请多多包涵。)合并两个数据帧与在琴弦某些模式

我有两个数据帧列A和B.我想将它们合并到名称列上。假设A有两列名称和数字。 A df的名称列的值为“.tony.x.rds”,“.tom.x.rds”等。

Name  Numbers 
.tony.x.rds 15.6 
.tom.x.rds 14.5 

B df有两列Name和ChaR。 B的名称列的值为“tony.x”,“tom.x”等。

Name ChaR 
tony.x ENG 
tom.x US 

两个DFS的列名称的主要元素是 “贝”, ”汤姆“ 等。

所以,” .tony.x.rds“等于“tony.x”“.tom.x.rds”等于“tom.x”

我曾尝试GSUB各种选择在A和B数据帧的名称栏中留下“tony”,“tom”等等。但是当我使用

StoRe<-merge(A,B, all=T) 

我ge和所有行的A和B,而不是单行。也就是说,对于每个“a”,“b”等等,在Numbers和ChaR列中分别有两行。例如:

Name Numbers ChaR 
tony 15.6 NA 
tony NULL ENG 
tom 14.5 NA 
tom NULL US 

它一直让我头痛。我请求你帮忙。

+1

不是我downvote。您想要加入两个数据框的实际情况是什么? –

+0

我想加入列名中的值。其实列名是固定名称,而.a.x.rds等于a。 – runjumpfly

+0

因此,可以肯定地说'.a.x.rds'包含'a.x'就足够了。 –

回答

3

一种可能的解决方案。我不完全确定你想要对字符串中的'x'做什么,我已经将它们保存在连接键中,但通过将\\1\\2更改为\\1,您只保留第一个字母。

a <- data.frame(
    Name = paste0(".", c("tony", "tom", "foo", "bar", "foobar"), ".x.rds"), 
    Numbers = rnorm(5) 
) 

b <- data.frame(
    Name = paste0(c("tony", "tom", "bar", "foobar", "company"), ".x"), 
    ChaR = LETTERS[11:15] 
) 

# String consists of 'point letter1 point letter2 point rds'; replace by 
# 'letter1 letter2' 
a$Name_stand <- gsub("^\\.([a-z]+)\\.([a-z]+)\\.rds$", "\\1\\2", a$Name) 

# String consists of 'letter1 point letter2'; replace by 'letter1 letter2' 
b$Name_stand <- gsub("^([a-z]+)\\.([a-z]+)$", "\\1\\2", b$Name) 

result <- merge(a, b, all = TRUE, by = "Name_stand") 

输出:

#> result 
# Name_stand  Name.x  Numbers Name.y ChaR 
#1  barx .bar.x.rds 1.38072696  bar.x M 
#2 companyx   <NA>   NA company.x O 
#3 foobarx .foobar.x.rds -1.53076596 foobar.x N 
#4  foox .foo.x.rds 1.40829287  <NA> <NA> 
#5  tomx .tom.x.rds -0.01204651  tom.x L 
#6  tonyx .tony.x.rds 0.34159406 tony.x K 

另一个,也许一定程度上更坚固(到琴弦的变体如“tom.rds”并且将仍然被链接“汤姆”;这当然也可以成为一个缺点)/

# Remove the rds from a$Name 
a$Name_stand <- gsub("rds$" , "", a$Name) 
# Remove all non alpha numeric characters from the strings 
a$Name_stand <- gsub("[^[:alnum:]]", "", a$Name_stand) 
b$Name_stand <- gsub("[^[:alnum:]]", "", b$Name) 

result2 <- merge(a, b, all = TRUE, by = "Name_stand") 
+0

感谢您的回应。其实a和b是公司名称。所以它可能是.tony.ltd.rds和tony.ltd – runjumpfly

+1

@runjumpfly在这种情况下,您可以使用'[a-z] +'而不是'[a-z]'。 –

+0

我几乎没有使用过gsub的经验。所以请看我编辑并让我知道如何使用你的解决方案 – runjumpfly