【发布时间】:2019-03-08 00:15:40
【问题描述】:
我有一个由树状信息列组成的 data.frame 对象。例如,我搜索了一组特征 (query_name) 并返回了一组潜在匹配项 (match_name)。每场比赛都有一个关联的位置,分为continent、country、region 和town。
我想解决的问题是,对于给定的query_name,找到所有潜在匹配项共有的位置信息。
例如,用这个示例数据:
query_name <- c(rep("feature1", 3), rep("feature2", 2), rep("feature3", 4))
match_name <- paste0("match", seq(1:9))
continent <- c(rep("NorthAmerica", 3), rep("NorthAmerica", 2), rep("Europe", 4))
country <- c(rep("UnitedStates", 3), rep("Canada", 2), rep("Germany", 4))
region <- c(rep("NewYork", 3), "Ontario", NA, rep("Bayern", 2), rep("Berlin", 2))
town <- c("Manhattan", "Albany", "Buffalo", "Toronto", NA, "Munich", "Nuremberg", "Berlin", "Frankfurt")
data <- data.frame(query_name, match_name, continent, country, region, town)
我们会生成这个 data.frame 对象:
query_name match_name continent country region town
1 feature1 match1 NorthAmerica UnitedStates NewYork Manhattan
2 feature1 match2 NorthAmerica UnitedStates NewYork Albany
3 feature1 match3 NorthAmerica UnitedStates NewYork Buffalo
4 feature2 match4 NorthAmerica Canada Ontario Toronto
5 feature2 match5 NorthAmerica Canada <NA> <NA>
6 feature3 match6 Europe Germany Bayern Munich
7 feature3 match7 Europe Germany Bayern Nuremberg
8 feature3 match8 Europe Germany Berlin Berlin
9 feature3 match9 Europe Germany Berlin Frankfurt
我希望就如何构造一个将产生以下结果的函数获得建议。请注意,共享位置信息现在使用; 分隔符连接和分隔。
- Feature1 仅在
town信息上有所不同,因此返回的字符串包含continent到region信息。 - Feature2 在
region或town在此处的两个匹配项中不同,因为两个匹配项之一不包含任何信息。尽管如此,缺乏信息被认为与有信息的值不同,因此特征2匹配的唯一共同点是continent和country。 - Feature3 包含共享的
continent和country信息,但region和town不同,因此只保留continent和country。
希望输出文件如下所示:
query_name location_output
feature1 NorthAmerica;UnitedStates;NewYork;
feature2 NorthAmerica;Canada;;
feature3 Europe;Germany;;
感谢您提供的任何建议。 干杯!
【问题讨论】: