简体   繁体   English

在R中嵌套for循环以实现状态组合

[英]Nested for loop in R for combination of states

I have two dataframes in R, statedata with "state" being a column in it and topstatedata, with "topstate" being a column in it. 我在R中有两个数据框,其中statedata是“ state”的一列,而topstatedata是“ topstate”,是其中的一列。 Total topstates are 5 and total states are 26. I want to run a nested loop for getting the following combination in my data, so that each of topstate forms a combination with a state. topstate的总数为5,state的总数为26。我想运行一个嵌套循环以在数据中获取以下组合,以使topstate的每一个与一个状态形成组合。 Something like this- 像这样的东西

topstate   state
CA         AB
TX         AB
NJ         AB
FL         AB
NY         AB
CA         AE
TX         AE
NJ         AE
FL         AE
NY         AE

..... and so on Please suggest me an R code for such output.Thanks .....依此类推,请为我建议这样的输出的R代码。

You can use the function expand.grid in the following way. 您可以按以下方式使用expand.grid函数。 I made up my own data.frames, so you will need to specify whatever df1 and df2 are in your script. 我组成了自己的data.frames,因此您需要指定脚本中的df1和df2。

df1 <- data.frame(topstate=c("CA","TX","NJ","FL","NY"))
df2 <- data.frame(state=c("AB","AE"))
result <- expand.grid(topstate=unique(df1$topstate),state=unique(df2$state))
result

   topstate state
1        CA    AB
2        TX    AB
3        NJ    AB
4        FL    AB
5        NY    AB
6        CA    AE
7        TX    AE
8        NJ    AE
9        FL    AE
10       NY    AE

You don't need a loop. 您不需要循环。 This will do the trick: 这将达到目的:

setNames(data.frame(unique(topstatedata$topstate), 
                    rep(unique(statedata$state),
                        each = length(unique(topstatedata$topstate)))), 
         names(statedata)))

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

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