每个项目每行迭代排列 [英] Iterate permutation per row per item
本文介绍了每个项目每行迭代排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想操纵数据来使用ggnet进行网络分析。
I would like to manipulate data to do network analysis using ggnet.
数据集采用csv形式,如下所示:
The dataset is in csv form and looks like this:
offers
{9425, 5801, 18451, 17958, 16023, 7166}
{20003, 17737, 4031, 5554}
{19764, 5553, 5554}
我想打破数组,并迭代换行所有项目每一行作为一对2.因此最终输出应如下所示:
What I would like to break the array, and iterate to permute all the items each row as a pair of 2. So the ultimate output should look like:
print list(itertools.permutations([1,2,3,4], 2)) per row to create:
(9425, 5801)
(9425, 18451)
(9425, 17958)
(9425, 16023)
(9425, 7166)
(5801, 18451)
(5801, 17958)
(5801, 16023)
(5801, 7166)
...
我可以用R或Python来做这件事。
有任何解决此问题的建议吗?
I could use either R or Python to do this. Any suggestions to solve this problem?
推荐答案
另一个R解决方案,假设您的文件中有更多行。
Another R solution, assuming there are more rows in your file.
# read in csv file as list of integers (each row in csv = 1 list element)
offers <- readLines("offers.csv") %>% strsplit(",") %>% lapply(as.integer)
# create permutation pairs for each element in the list
permutation.list <- lapply(seq_along(offers), function(i) {t(combn(offers[[i]], m = 2))})
# combine all permutation pairs into 1 data frame
permutation.data.frame <- plyr::ldply(permutation.list, data.frame)
以下是根据提供的样本数据得出的结果:
Below are the results based on the sample data provided:
> permutation.list
[[1]]
[,1] [,2]
[1,] 9425 5801
[2,] 9425 18451
[3,] 9425 17958
[4,] 9425 16023
[5,] 9425 7166
[6,] 5801 18451
[7,] 5801 17958
[8,] 5801 16023
[9,] 5801 7166
[10,] 18451 17958
[11,] 18451 16023
[12,] 18451 7166
[13,] 17958 16023
[14,] 17958 7166
[15,] 16023 7166
[[2]]
[,1] [,2]
[1,] 20003 17737
[2,] 20003 4031
[3,] 20003 5554
[4,] 17737 4031
[5,] 17737 5554
[6,] 4031 5554
[[3]]
[,1] [,2]
[1,] 19764 5553
[2,] 19764 5554
[3,] 5553 5554
> permutation.data.frame
X1 X2
1 9425 5801
2 9425 18451
3 9425 17958
4 9425 16023
5 9425 7166
6 5801 18451
7 5801 17958
8 5801 16023
9 5801 7166
10 18451 17958
11 18451 16023
12 18451 7166
13 17958 16023
14 17958 7166
15 16023 7166
16 20003 17737
17 20003 4031
18 20003 5554
19 17737 4031
20 17737 5554
21 4031 5554
22 19764 5553
23 19764 5554
24 5553 5554
这篇关于每个项目每行迭代排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文