繁体   English   中英

如何合并其中column1是column2的子字符串的数据框

[英]How to merge data frames where column1 is substring of column2

我有一个数据框,并希望根据列df $ name的值对每一行进行分类。 对于分类,我有一个带有列tl $ name和tl $ type的两列数据帧tl。 我想在类似条件下合并两个数据框,grepl(tl $ name,df $ name),而不是df $ name = tl $ name。

我已经尝试通过循环遍历df中的所有行并查看与tl匹配的位置,但这似乎非常耗费时间。

例如:

DF

  name        
# African elephant    
# Indian elephant    
# Silverback gorilla     
# Nile crocodile   
# White shark       

TL

  name        type
# elephant    mammal
# gorilla     mammal
# crocodile   reptile
# shark       fish

另一个想法:

library(tidyverse)

df %>%
  separate(name, into = c("t", "name")) %>%
  left_join(tl)

这使:

#           t      name    type
#1    African  elephant  mammal
#2     Indian  elephant  mammal
#3 Silverback   gorilla  mammal
#4       Nile crocodile reptile
#5      White     shark    fish

我们可以删除与子sub通过匹配一个或多个非空格( \\\\S+后面跟着一个或多个空格() \\\\s+从一开始() ^字符串),与空白替换它( "" )并与第二个数据集('tl') merge

merge(transform(df, name = sub("^\\S+\\s+", "", name)), tl)
#      name    type
#1 crocodile reptile
#2  elephant  mammal
#3  elephant  mammal
#4   gorilla  mammal
#5     shark    fish

如果我们需要更新第一个数据集,

df$type <- with(df, tl$type[match(sub("^\\S+\\s+", "", name), tl$name)])
df

  name        
# African elephant    
# Indian elephant    
# Silverback gorilla     
# Nile crocodile   
# White shark       
tl

  name        type
# elephant    mammal
# gorilla     mammal
# crocodile   reptile
# shark       fish

我想这就是你想要做的

df<-csplit(df, splitcols="name", sep=" ")

上面的命令会将该列拆分为两列,其中包含name.1和name.2列名。

colnames(df)<-c("name","type")

上面的命令将为合并提供正确的列名

df_tl<-merge(x=df, y=tl, by="type",all=True)

上面的代码应该为您提供所需的输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM