R 查找具有相同列值的所有序列
我有以下数据框:R 查找具有相同列值的所有序列,r,R,我有以下数据框: ╔══════╦═════════╗ ║ Code ║ Airline ║ ╠══════╬═════════╣ ║ 1 ║ AF ║ ║ 1 ║ KL ║ ║ 8 ║ AR ║ ║ 8 ║ AZ ║ ║ 8 ║ DL ║ ╚══════╩═════════╝ dat <- structure(list(Code = c(1L, 1L, 8L, 8L, 8L), Airline = stru
╔══════╦═════════╗
║ Code ║ Airline ║
╠══════╬═════════╣
║ 1 ║ AF ║
║ 1 ║ KL ║
║ 8 ║ AR ║
║ 8 ║ AZ ║
║ 8 ║ DL ║
╚══════╩═════════╝
dat <- structure(list(Code = c(1L, 1L, 8L, 8L, 8L), Airline = structure(c(1L,
5L, 2L, 3L, 4L), .Label = c("AF ", "AR ", "AZ ", "DL", "KL "
), class = "factor")), .Names = c("Code", "Airline"), class = "data.frame", row.names = c(NA,
-5L))
伪代码是任何命令式语言都可以使用的
for each code
lookup all rows in the table where the value = code
既然R不是那么以列表为导向,那么实现预期输出的最佳方式是什么
拆分
有帮助。这是一个完全可复制的编辑,不需要任何额外的软件包。使用OPs data.frame-在OP添加可复制数据集后对其进行更改
# strip white space in Airline names:
dat$Airline <- gsub(" ","",dat$Airline)
li <- split(dat,factor(dat$Code))
do.call("rbind",lapply(li,function(x)
data.frame(Airline = x[1,2],
SharedWith = paste(x$Airline[-1]
,collapse=",")
))
)
#去除航空公司名称中的空白:
dat$Airline您可以在dplyr
library(dplyr)
df %>% group_by(code) %>% mutate(SharedWith = paste(sort(Airline), collapse = ', ')) %>% ungroup() %>% select(Airline, SharedWith)
可能会有一条更有效的路线,但应该是:
# example data
d <- data.frame(code = c(1,1,8,8,8),
airline = c("AF","KL","AR","AZ","DL"),
stringsAsFactors = FALSE)
# merge d to itself on the code column. This isn't necessarily efficient
d2 <- merge(d, d, by = "code")
# prune d2 to remove occasions where
# airline.x and airline.y (from the merge) are equal
d2 <- d2[d2[["airline.x"]] != d2[["airline.y"]], ]
# construct the combinations for each airline using a split, apply, combine
# then, use stack to get a nice structure for merging
d2 <- stack(
lapply(split(d2, d2[["airline.x"]]),
function(ii) paste0(ii$airline.y, collapse = ",")))
# merge d and d2. "ind" is a column produced by stack
merge(d, d2, by.x = "airline", by.y = "ind")
# airline code values
#1 AF 1 KL
#2 AR 8 AZ,DL
#3 AZ 8 AR,DL
#4 DL 8 AR,AZ
#5 KL 1 AF
#示例数据
d使用数据的多个选项。表包:
1)使用strsplit
,粘贴
&按行操作:
library(data.table)
setDT(dat)[, Airline := trimws(Airline) # this step is needed to remove the leading and trailing whitespaces
][, sharedwith := paste(Airline, collapse = ','), Code
][, sharedwith := paste(unlist(strsplit(sharedwith,','))[!unlist(strsplit(sharedwith,',')) %in% Airline],
collapse = ','), 1:nrow(dat)]
其中:
> dat
Code Airline sharedwith
1: 1 AF KL
2: 1 KL AF
3: 8 AR AZ,DL
4: 8 AZ AR,DL
5: 8 DL AR,AZ
Code air shared
1: 1 AF KL
2: 1 KL AF
3: 8 AR AZ,DL
4: 8 AZ AR,DL
5: 8 DL AR,AZ
Code Airline SharedWith
(int) (chr) (chr)
1 1 AF KL
2 1 KL AF
3 8 AR AZ, DL
4 8 AZ AR, DL
5 8 DL AR, AZ
2)使用strsplit
和粘贴与mapply
而不是by=1:nrow(dat)
:
这会给你同样的结果
3)或使用带有粘贴的CJ
功能(灵感来自@zx8754的扩展.grid
解决方案):
其中:
> dat
Code Airline sharedwith
1: 1 AF KL
2: 1 KL AF
3: 8 AR AZ,DL
4: 8 AZ AR,DL
5: 8 DL AR,AZ
Code air shared
1: 1 AF KL
2: 1 KL AF
3: 8 AR AZ,DL
4: 8 AZ AR,DL
5: 8 DL AR,AZ
Code Airline SharedWith
(int) (chr) (chr)
1 1 AF KL
2 1 KL AF
3 8 AR AZ, DL
4 8 AZ AR, DL
5 8 DL AR, AZ
使用dplyr
和tidyr
获得所需解决方案的解决方案(灵感来自@jaimedash):
一种igraph
方法
library(igraph)
g <- graph_from_data_frame(dat)
# Find neighbours for select nodes
ne <- setNames(ego(g,2, nodes=as.character(dat$Airline), mindist=2), dat$Airline)
ne
#$`AF `
#+ 1/7 vertex, named:
#[1] KL
#$`KL `
#+ 1/7 vertex, named:
#[1] AF
---
---
# Get final format
data.frame(Airline=names(ne),
Shared=sapply(ne, function(x)
paste(V(g)$name[x], collapse=",")))
# Airline Shared
# 1 AF KL
# 2 KL AF
# 3 AR AZ,DL
# 4 AZ AR,DL
# 5 DL AR,AZ
库(igraph)
g使用expand.grid和aggregate:
do.call(rbind,
lapply(split(dat, dat$Code), function(i){
x <- expand.grid(i$Airline, i$Airline)
x <- x[ x$Var1 != x$Var2, ]
x <- aggregate(x$Var2, list(x$Var1), paste, collapse = ",")
colnames(x) <- c("Airline", "SharedWith")
cbind(Code = i$Code, x)
}))
# output
# Code Airline SharedWith
# 1.1 1 AF KL
# 1.2 1 KL AF
# 8.1 8 AR AZ,DL
# 8.2 8 AZ AR,DL
# 8.3 8 DL AR,AZ
do.call(rbind,
lapply(拆分(dat,dat$代码),函数(i){
我想你需要的只是一张表格
dat <- structure(list(Code = c(1L, 1L, 8L, 8L, 8L),Airline = structure(c(1L, 5L, 2L, 3L, 4L),.Label = c("AF", "AR", "AZ", "DL", "KL"),class = "factor")),.Names = c("Code", "Airline"),class = "data.frame", row.names = c(NA, -5L))
tbl <- crossprod(table(dat))
diag(tbl) <- 0
# Airline
# Airline AF AR AZ DL KL
# AF 0 0 0 0 1
# AR 0 0 1 1 0
# AZ 0 1 0 1 0
# DL 0 1 1 0 0
# KL 1 0 0 0 0
dd <- data.frame(Airline = colnames(tbl),
shared = apply(tbl, 1, function(x)
paste(names(x)[x > 0], collapse = ', ')))
merge(dat, dd)
# Airline Code shared
# 1 AF 1 KL
# 2 AR 8 AZ, DL
# 3 AZ 8 AR, DL
# 4 DL 8 AR, AZ
# 5 KL 1 AF
dat将以下内容作为注释,作为答案发布,只是因为这样可以更方便地设置格式
for each code
lookup all rows in the table where the value = code
嗯……对不起,我不明白这个psedudocode与您想要的输出有什么关系
+--------------------+
| Airline SharedWith |
+--------------------+
| AF "KL" |
| KL "AF" |
| AR "AZ","DL" |
+--------------------+
此伪代码的结果应该是:
+---------------------+
+ Code + Airlines +
+---------------------+
+ 1 + AF, KL +
+ 2 + AR, AZ, DL +
+---------------------+
就是
codes <- unique(dat$Code)
data.frame(Code=codes, Airlines = sapply(codes, function(x) paste(subset(dat, Code %in% x)$Airline, collapse=",")))
codes您可以使用tidyr
的nest
快速完成此操作(尽管除非您首先将航空公司作为要素转换为字符,否则速度会慢一些)和合并
library(tidyr)
dat$Airline <- as.character(dat$Airline)
new_dat <- merge(dat, dat %>% nest(-Code, .key= SharedWith), by="Code")
与其他解决方案相比,此解决方案的一个优点是:SharedWith
成为data.frame的列表列,而不是一个字符
> str(new_dat$SharedWith)
List of 5
$ :'data.frame': 2 obs. of 1 variable:
..$ Airline: chr [1:2] "AF" "KL"
$ :'data.frame': 2 obs. of 1 variable:
..$ Airline: chr [1:2] "AF" "KL"
$ :'data.frame': 3 obs. of 1 variable:
..$ Airline: chr [1:3] "AR" "AZ" "DL"
$ :'data.frame': 3 obs. of 1 variable:
..$ Airline: chr [1:3] "AR" "AZ" "DL"
$ :'data.frame': 3 obs. of 1 variable:
..$ Airline: chr [1:3] "AR" "AZ" "DL"
因此,您可以很容易地(albiet不漂亮地)索引出共享值的向量,如:
> new_dat$SharedWith[[1]]$Airline
[1] "AF" "KL"
与其使用strsplit
或类似的,不如以一种可以提供给R的形式提供样本输入。这样对想要帮助你的人来说更容易。使用dput
将数据输出到一种可以轻松导入的形式,而不是面向列表的形式。哈哈,这只是R中的主要数据结构。我也会这样做。我们可以同意这一点。事实上…数据框是一个列表:)我设法从dplyr中通过group_by获得了类似的结果。但是我陷入了查找每列的所有排列的困境。请尝试:df%>%group_by(code)%%>%mutate(SharedWith=paste(sort(Airline),collapse=','))
这也将航空公司保留在同一列中。太好了!这要好得多!但我需要排除同一家航空公司,因为现在它也与自己共享。@AndreiVaranovich adplyr
免费解决方案与base R,这应该会给出您上面指定的输出…但是–我不知道您在t中真正想做什么他结束了。但我有一种预感,这种方法有点不成熟。@AndreiVaranovich这能解决重复问题吗?这种解决方案的优点是你不需要另一个软件包。也就是说,我喜欢@Dellactiatus Maximus,因为data.table
确实很酷,而且可能是计算时间最快的解决方案。“但这应该飞起来”——很好的双关语。所有的人都欢呼表。非常好地使用它
> str(new_dat$SharedWith)
List of 5
$ :'data.frame': 2 obs. of 1 variable:
..$ Airline: chr [1:2] "AF" "KL"
$ :'data.frame': 2 obs. of 1 variable:
..$ Airline: chr [1:2] "AF" "KL"
$ :'data.frame': 3 obs. of 1 variable:
..$ Airline: chr [1:3] "AR" "AZ" "DL"
$ :'data.frame': 3 obs. of 1 variable:
..$ Airline: chr [1:3] "AR" "AZ" "DL"
$ :'data.frame': 3 obs. of 1 variable:
..$ Airline: chr [1:3] "AR" "AZ" "DL"
> new_dat$SharedWith[[1]]$Airline
[1] "AF" "KL"