递归中的python/R字符串连接
数据看起来像这样递归中的python/R字符串连接,python,r,recursion,Python,R,Recursion,数据看起来像这样 A, B, YYMM 1, 1, 1707 1, 2, 1707 1, 3, 1707 2, 3, 1706 2, 1, 1706 2, 2, 1706 2, 4, 1706 3, 3, 1705 3, 2, 1705 3, 1, 1704 3, 4, 1704 我希望输出作为连接A、B的源和目标,如下所示: Source, Target (1,1), (1,2) (1,1), (1,3) (1,2), (1,3) (2,3), (2,1) (2,3), (2,2) (2,3
A, B, YYMM
1, 1, 1707
1, 2, 1707
1, 3, 1707
2, 3, 1706
2, 1, 1706
2, 2, 1706
2, 4, 1706
3, 3, 1705
3, 2, 1705
3, 1, 1704
3, 4, 1704
我希望输出作为连接A、B的源和目标,如下所示:
Source, Target
(1,1), (1,2)
(1,1), (1,3)
(1,2), (1,3)
(2,3), (2,1)
(2,3), (2,2)
(2,3), (2,4)
(2,1), (2,2)
(2,1), (2,4)
(2,2), (2,4)
(3,3), (3,2)
(3,1), (3,4)
基本上,我想做的是通过YYMM计算所有可能的案例数量,以查看两列之间的关系
起初,我考虑通过范围I:max-I和I+1到max来连接它们,但是尽管这些值是整数,我觉得应该将它们作为字符串使用,因为顺序很重要
是否有一个函数可以根据我的需要操作数据集?感谢您的建议。一旦您按照
YYMM
对数据进行分组,您就可以使用itertools.compositions
来满足您的需求:一旦您按照YYMM
对数据进行分组,您就可以使用itertools.compositions
来满足您的需求:这里有一个选项。我们可以使用combn
功能和tidyverse
包的帮助
library(tidyverse)
dt2 <- dt %>%
unite(Value, A, B, sep = ",") %>%
split(f = .$YYMM) %>%
map(function(x){
as_data_frame(t(combn(x$Value, m = 2)))
}) %>%
bind_rows(.id = "YYMM") %>%
arrange(desc(YYMM)) %>%
select(Source = V1, Target = V2)
dt2
# A tibble: 11 x 2
Source Target
<chr> <chr>
1 1,1 1,2
2 1,1 1,3
3 1,2 1,3
4 2,3 2,1
5 2,3 2,2
6 2,3 2,4
7 2,1 2,2
8 2,1 2,4
9 2,2 2,4
10 3,3 3,2
11 3,1 3,4
库(tidyverse)
dt2%
单位(值,A,B,sep=“,”)%>%
拆分(f=.$YYMM)%>%
地图(功能(x){
作为数据帧(t(combn(x$Value,m=2)))
}) %>%
绑定行(.id=“YYMM”)%>%
排列(描述(YYMM))%>%
选择(源=V1,目标=V2)
dt2
#一个tibble:11x2
源目标
1 1,1 1,2
2 1,1 1,3
3 1,2 1,3
4 2,3 2,1
5 2,3 2,2
6 2,3 2,4
7 2,1 2,2
8 2,1 2,4
9 2,2 2,4
10 3,3 3,2
11 3,1 3,4
这里有一个选项。我们可以使用combn
功能和tidyverse
包的帮助
library(tidyverse)
dt2 <- dt %>%
unite(Value, A, B, sep = ",") %>%
split(f = .$YYMM) %>%
map(function(x){
as_data_frame(t(combn(x$Value, m = 2)))
}) %>%
bind_rows(.id = "YYMM") %>%
arrange(desc(YYMM)) %>%
select(Source = V1, Target = V2)
dt2
# A tibble: 11 x 2
Source Target
<chr> <chr>
1 1,1 1,2
2 1,1 1,3
3 1,2 1,3
4 2,3 2,1
5 2,3 2,2
6 2,3 2,4
7 2,1 2,2
8 2,1 2,4
9 2,2 2,4
10 3,3 3,2
11 3,1 3,4
库(tidyverse)
dt2%
单位(值,A,B,sep=“,”)%>%
拆分(f=.$YYMM)%>%
地图(功能(x){
作为数据帧(t(combn(x$Value,m=2)))
}) %>%
绑定行(.id=“YYMM”)%>%
排列(描述(YYMM))%>%
选择(源=V1,目标=V2)
dt2
#一个tibble:11x2
源目标
1 1,1 1,2
2 1,1 1,3
3 1,2 1,3
4 2,3 2,1
5 2,3 2,2
6 2,3 2,4
7 2,1 2,2
8 2,1 2,4
9 2,2 2,4
10 3,3 3,2
11 3,1 3,4